c#调用c++ dll const char* String类型转换问题。传值,与接收返回值问题


C++原型
extern "C" __declspec(dllexport) const  char* GetUnicoide(const char* gb2312)
{
	int len = MultiByteToWideChar(CP_ACP, 0, gb2312, -1, NULL, 0);
	wchar_t* wstr = new wchar_t[len+1];
	memset(wstr, 0, len+1);
	MultiByteToWideChar(CP_ACP, 0, gb2312, -1, wstr, len);
	len = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, NULL, NULL);
	char* str = new char[len+1];
	memset(str, 0, len+1);
	WideCharToMultiByte(CP_UTF8, 0, wstr, -1, str, len, NULL, NULL);
	if(wstr) delete[] wstr;
	return str;
}

  

    C#调用
[DllImport("strlen.dll", CallingConvention = CallingConvention.Cdecl)]
extern static IntPtr GetUnicoide(string s);


                string a ="hello 123";
                IntPtr b = GetUnicoide(a);
                string c= Marshal.PtrToStringAnsi(b);
 
 

  

 
还有一种情况是C++ 中参数是  

const  char*

我们在C# 中通常是用String进行传值。某些情况下,我们传的数据在C++指针地址里可以很好的表示,但是用C#的 String是表示不出来或表示不完整的,这时候就鸡肋了。。

遇到这种情况
IntPtr 是可以很好的表示的。。。

  





免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM