I want to call my .NET code from unmanaged C++. My process entrypoint is .NET based, so I don't have to worry about hosting the CLR. I know it can be done using COM wrappers for .NET objects, but I would like to access individual static methods of managed classes, so COM isn't my shortest/easiest route.
CLR is in charge of taking the managed code, compiling it into machine code and then executing it. On top of that, runtime provides several important services such as automatic memory management, security boundaries, type safety etc. Contrast this to the way you would run a C/C++ program, also called "unmanaged code".
Difference between managed and unmanaged code? Managed code is the one that is executed by the CLR of the . NET framework while unmanaged or unsafe code is executed by the operating system. The managed code provides security to the code while undamaged code creates security threats.
So, by that definition all code compiled by traditional C/C++ compilers is 'unmanaged code'. Also, since it compiles to machine code and not an intermediate language it is non-portable.
This is responsible for things like memory management and garbage collection. So unmanaged simply runs outside of the context of the CLR. unsafe is kind of "in between" managed and unmanaged. unsafe still runs under the CLR, but it will let you access memory directly through pointers.
Take a look at the GCHandle class and the gcroot keyword, which provides a typesafe, templated wrapper around GCHandle.
You can use these to hold a reference to a CLR object (or a boxed value) in native code.
MSDN has a basic tutorial here.
Look at this solution: https://sites.google.com/site/robertgiesecke/Home/uploads/unmanagedexports The solution allows to call C# function from C by decorating your function with [DllExport] attribute (opposite of P/Invoke DllImport).
Exmaple:
C# code
class Test
{
[DllExport("add", CallingConvention = CallingConvention.StdCall)]
public static int Add(int left, int right)
{
return left + right;
}
}
C code:
extern "C" int add(int, int);
int main()
{
int z = add(5,10);
printf("The solution is found!!! Z is %i",z);
return 0;
}
Output:
The solution is found!!! Z is 15
Update: There is a question and a good answer in comments:
How do I include the dll in the unmanaged project?
You have to link to the .lib file that is generated upon compiling your C# code (https://msdn.microsoft.com/en-us/library/ba1z7822.aspx?f=255&MSPPError=-2147217396)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With