C++和C# DLL互相调用 CLR

最近项目需要,别人给的一个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

 

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值