Asi*_*sik 68
好的,教程.您有一个NativeClass要向C#公开的C++类.
class NativeClass {
public:
void Method();
};
Run Code Online (Sandbox Code Playgroud)
1)创建C++/CLI项目.链接到您的C++库和标头.
2)创建一个公开所需方法的包装类.例:
#include "NativeClass.h"
public ref class NativeClassWrapper {
NativeClass* m_nativeClass;
public:
NativeClassWrapper() { m_nativeClass = new NativeClass(); }
~NativeClassWrapper() { this->!NativeClassWrapper(); }
!NativeClassWrapper() { delete m_nativeClass; }
void Method() {
m_nativeClass->Method();
}
};
Run Code Online (Sandbox Code Playgroud)
3)在C#项目中添加对C++/CLI项目的引用.
4)在using语句中使用包装器类型:
using (var nativeObject = new NativeClassWrapper()) {
nativeObject.Method();
}
Run Code Online (Sandbox Code Playgroud)
using语句确保调用Dispose(),它会立即运行析构函数并销毁本机对象.否则你会有内存泄漏,可能会死得很厉害(不是你,程序).注意:为您神奇地创建了Dispose()方法.