最近项目需要,别人给的一个C#做的DLL接口,小弟用的还是MFC.这里就涉及到托管代码
首先导入DLL和创建对象
1.导入库 #using "dll路径",dll没有头文件,不用#include
2.假如命名空间, using namespace Class;
3.对象都是以指针出现,而c++/clr指针不是*是用^访问托管对象, 创建的关键字是gcnew(和c++本地区分)
另外clr里面的gcnew出来的对象不用delete(也没有gcdelete相关),猜想沿用c#自动回收 菜鸟猜测不喜轻喷
做完上述几部,对象里面的接口和参数都可以看到就正常导入
字符串类型转换
System.String^转std::string
void MarshalString ( String ^ s, wstring& os ) {
using namespace Runtime::InteropServices;
const wchar_t* chars =
(const wchar_t*)(Marshal::StringToHGlobalUni(s)).ToPointer();
os = chars;
Marshal::FreeHGlobal(IntPtr((void*)chars));
}
CString转System.String^
strDeviceID = gcnew System::String(strResourceID.GetBuffer());
strResourceID.ReleaseBuffer();
System.String^转CString
CString strRet(sysstrRet);
到这里基本上代码基本修改部分完了,后面是编译环境
原有项目属性里面,相应用到的库也需要修改
1.C/C++->General->Common Language RunTime Support设置成Common Language RunTime Support(/clr)
2.C/C++->Code Generation->Enable String Pooling设置成Yes(/GF)
这两个属性缺一不可,
第一个缺失就是编译一堆的错误(clr里面的类没导入)
第二个缺失报错:An unhandled exception of type 'System.IO.FileLoadException' occurred in Unknown Module.Additional information: Could not load file or assembly '项目名, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. Could not find or load a type. (Exception from HRESULT: 0x80131522)
C#调用C++做的DLL,就基本上直接引用创建对象用
这里感谢
https://blog.csdn.net/xiaominggunchuqu/article/details/79020541
https://www.cnblogs.com/yilang/p/11859212.html