使用P/Invoke通过指针实例化C#中的C ++类 [英] Instantiating a C++ class in C# using P/Invoke via a pointer

查看:112
本文介绍了使用P/Invoke通过指针实例化C#中的C ++类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从C#应用程序中的非托管DLL mscorpe.dll导入CreateICeeFileGen()函数,以生成PE文件.此函数返回指向在此处定义的对象的指针,是否存在我可以通过C#访问此类中的字段的任何方式,还是需要编写非托管包装DLL?

我当前使用的代码如下:-

[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);    

NB :我知道您可以使用.net库执行类似的操作,但是出于我的目的,我需要使用非托管库.

解决方案

您需要一个包装器库才能使用C#中的类.

最好的选择是使用C ++/CLI创建包装器,该包装器可以直接调用非托管函数并使用托管类公开细节.这样就无需使用P/Invoke了.

(好吧,从技术上讲,如果您知道类的布局,就可以用指针算术弄乱访问这些字段的方法,但这将是非常脆弱和混乱的,以这种方式尝试调用虚函数将非常难看). /p>

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.

解决方案

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

这篇关于使用P/Invoke通过指针实例化C#中的C ++类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆