Search code examples
c#.netpinvoke

Instantiating a C++ class in C# using P/Invoke via a pointer


I am importing the CreateICeeFileGen() function from the unmanaged DLL mscorpe.dll in a C# application, in order to generate a PE file. This function returns a pointer to an C++ object defined here, is there any way I can access fields from this class via C# or do I need to write an unmanaged wrapper DLL?

The code I'm using currently is as follows:-

[DllImport(@"C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\mscorpe.dll", EntryPoint = "CreateICeeFileGen")]
static extern void CreateICeeFileGen(out IntPtr iceeFileGenPointer);
...
IntPtr filePtr;
CreateICeeFileGen(out filePtr);    

N.B.: I know you can do similar things with .net libraries but I need to use unmanaged libraries for my purposes.


Solution

  • You need a wrapper library to be able to use the class from C#.

    The best bet would be to create the wrapper using C++/CLI, which can directly call the unmanaged function and expose the details with a managed class. This will eliminate the need to use P/Invoke for anything.

    (Well, technically if you know the class layout you could mess around with pointer arithmetic to access the fields, but this would be very fragile and messy, and trying to call virtual functions in this way would be extremely ugly).