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 是可以很好的表示的。。。