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

試著忘記壹切 提交于 2020-01-06 02:28:14

问题


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.


回答1:


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).




回答2:


It looks like COM class/interface. Can you not just use COM instead?



来源:https://stackoverflow.com/questions/197720/instantiating-a-c-class-in-c-sharp-using-p-invoke-via-a-pointer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!