Call managed API from unmanaged code RRS feed

  • Question

  • I have created an API in C# that I wish to call from unmanaged C++ code.  I have found a few articles which detail how to disassemble, alter, and reassemble the MSIL once it is compiled.  The problem is that my assemblies will all be generated by Platform Builder as part of a complete OS image, so I do not have the luxury of editing the MSIL by hand, after the fact.

    I have also found articles that talk about passing a delegate to the unmanaged code via:

    delegate int MyUnmanagedCdeclDelegate(int param);
    But the only way that I have seen this used is for the C# program to first call the unmanaged code so that it can pass the function pointer, and then the unmanaged code can use it (so long as the delegate does not get garbage collected.)

    Is there any way that the unmanaged code can initiate this whole process?  Like I said, I am trying to create an API, so I need any arbitrary unmanaged code to be able to call into my managed dll.  Is this at all possible?  I wouldn't even mind having some sort of intermediate dll that is called from the unmanaged code, which in turn calls into the managed dll.

    I could really use a push in the right direction here, if this is even possible.  I have read through heaps of articles, but they all seem to point me in the same direction: The C# program passes a function pointer to the native method, and then calls other native methods which use the callback delegate that was passed.  Maybe I am missing something, but I don't understand the utility of that setup.

    Thanks in advance for any tips or articles that can help.

    Tuesday, June 29, 2010 2:57 PM


  • The only way this'll work without modifiying the MSIL after compilation is to expose the code as a COM object and create an instance of it in from your native code, C# cannot export single functions without that (cool, but mostly unsupported hack where you modify the IL).  Another option thats maybe worth a shot iv'e seen articles on codeproject that automate the modifying of the IL and recompile, perhaps you could use that as a post build step and still have the platform builder be happy with it?
    • Marked as answer by SamAgain Tuesday, July 6, 2010 7:08 AM
    Tuesday, June 29, 2010 4:01 PM