包装C#C ++ [英] Wrapping C# C++
问题描述
我想换用C ++ / CLI本机库。这是一个与原始类型的工作。但是,在以下情况下,它更复杂的:
I would like to wrap a native library with C++/CLI. It's work with primitive type. But in the following case, it's more complicated :
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);
}
};
如何来包装呢?由于本机code C ++不知道ISampleInterface类型...(同样的问题与虚拟类)
How to wrap this ? Because the native code C++ doesn't know the ISampleInterface type... (Same question with a virtual class)
谢谢你。
推荐答案
有在code段一些错误。让我们先从一个干净的例子,首先声明的本机类:
There are some mistakes in the code snippet. Let's start with a clean example, declaring the native class first:
#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 ::方法()。所有这包装所要做的就是简单地委托调用相应的管理接口方法。通常需要一个简单的一行,除非参数类型转换。像这样的:
So what you need is a native wrapper class that derives from INativeInterface so that you can pass an instance of it to NativeClass::Method(). All that this wrapper has to do is simply delegate the call to the corresponding managed interface method. Usually a simple one-liner unless argument types need to be converted. Like this:
#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();
}
};
现在你的方法实现变得简单:
Now your method implementation becomes easy:
void Method(IManagedInterface^ i) {
NativeInterfaceWrapper wrap(i);
m_nativeClass->Method(&wrap);
}
这篇关于包装C#C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!