[英]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类型...(与虚拟类相同的问题)
谢谢。
如果您的本机类需要回调到.NET代码,则需要使用gcroot
模板。 Wuth,您可以将托管对象存储在非托管类中。 在这个非托管类中,您可以使用本机“回调”,然后使用存储在`gcroot'中的成员回调到托管代码(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 <msclr\gcroot.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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.