Wrapping C# C++
Wrapping C# C++
我想用C++/CLI包装本机库。这是原始类型的作品。但在以下情况下,情况更为复杂:
interface ISampleInterface
{
void SampleMethod();
}
public ref class NativeClassWrapper {
NativeClass* m_nativeClass;
public:
NativeClassWrapper() { m_nativeClass = new NativeClass(); }
~NativeClassWrapper() { delete m_nativeClass; }
void Method(ISampleInterface ^i) {
???
m_nativeClass->Method(i);
}
};
如何包装这个?因为本机代码C++不知道ISampleInterface类型。。。(虚拟课堂的问题相同)
谢谢你。
代码片段中存在一些错误。让我们从一个干净的例子开始,首先声明本机类:
#pragma unmanaged
class INativeInterface {
public:
virtual void SampleMethod() = 0;
};
class NativeClass {
public:
void Method(INativeInterface* arg);
};
以及托管接口:
#pragma managed
public interface class IManagedInterface
{
void SampleMethod();
};
因此,您需要的是一个从INativeInterface派生的本机包装类,这样您就可以将其实例传递给NativeClass::Method()。这个包装器所要做的就是简单地将调用委托给相应的托管接口方法。通常是一个简单的单行,除非需要转换参数类型。像这样:
#pragma managed
#include <msclrgcroot.h>
class NativeInterfaceWrapper : public INativeInterface {
msclr::gcroot<IManagedInterface^> itf;
public:
NativeInterfaceWrapper(IManagedInterface^ arg) : itf(arg) {};
virtual void SampleMethod() {
itf->SampleMethod();
}
};
现在,您的方法实现变得很容易:
void Method(IManagedInterface^ i) {
NativeInterfaceWrapper wrap(i);
m_nativeClass->Method(&wrap);
}
如果本机类需要回调到.NET代码中,则需要使用gcroot
模板。这样,您就可以将托管对象存储在非托管类中。在这个非托管类中,您可以使用本机"回调",然后使用存储在"gcroot"中的成员回调到托管代码中(ISampleInterface)。
另请参阅:
- 如何:在本机类型中声明句柄
- 如何:在本机函数中保持对象引用
- 用C++/CLI编写高效可靠代码的最佳实践