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