How to call managed code from unmanaged code?

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)

Leave a Comment