C++调用C# DLL过程以及问题总结

  1. 将C#编写的DLL文件放置在C++的可执行程序目录
  2. 代码中使用 #using引用C#编写的DLL文件
    C# DLL实现代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestDLL
{
    public class Test
    {
    	public string demo()
        {
 			return "OK";
 		}
    }
}

c++调用代码:

#using "..\Release\TestDLL.dll"   //此处使用 .\TestDLL.dl会报错,原因未知
using namespace TestDLL
......
......
......
MathTest ^a = gcnew MathTest();  
String^ s=a->demo();
  1. 配置C++项目的属性配置:添加公共语言运行支持
    在这里插入图片描述

  2. 问题总结

  • 使用C++/clr语法,采用正确的方式访问托管对象,即:使用帽子“^”,而不是“*”
  • C#返回值为int或者bool等c#和c++都支持的类型时,可以直接使用,若C#返回值为C#中的string时,c++接收字符串需要用System::String,然后将String转换为c++支持的char*或者CString
    具体实现如下:
MathTest ^a = gcnew MathTest();  
	System::String^ s=a->demo();
	CString str1;
	using namespace Runtime::InteropServices; 
	const char* chars = (const char*)(Marshal::StringToHGlobalAnsi(s)).ToPointer(); 
	str1.Format("%s",chars);
	Marshal::FreeHGlobal(IntPtr((void*)chars)); 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值