[英]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.