建立C++项目时选择生成DLL库
C++示例代码 dllmain.cpp 生成test.dll
#include "ClassHeader.h" //类定义(声明)头文件
extern "C" _declspec(dllexport) ClassName* createClass(){ //创建类对象,返回指针
return new ClassName();
}
extern "C" _declspec(dllexport) void deleteClass(ClassName* pObject){
if (pObject){
delete pObject;
pObject = 0;
}
}
extern "C" _declspec(dllexport) int callFunction(ClassName* pObject, type functionParameters){ //函数参数
if (pObject){
return pObject->functionName(functionParameters);
}
}
C#中相应代码
#region PInvokes
[DllImport("test.dll")]
static public extern IntPtr createClass();
[DllImport("test.dll")]
static public extern void deleteClass(IntPtr pObject);
[DllImport("test.dll")]
static public extern int callFunction(IntPtr pObject, type parameters);
#endregion PInvoles
之后在C#中定义一个IntPtr类型的变量就可以操作C++的对象和函数了。
创建对象:
IntPtr pObj = createClass();
调用函数:
callFunction(pObj, functionParameters);
消除对象:
deleteClass(pObj);