C#string以string轉char*和以byte[]轉char*傳入C++

public static extern void editstring2(IntPtr ptr);
        [DllImport("dllfordebugdemo.dll", EntryPoint = "ansiunicode", CallingConvention = CallingConvention.Cdecl)]
        public static extern void ansiunicode(string ptr);
        [DllImport("dllfordebugdemo.dll", EntryPoint = "ansiunicode", CallingConvention = CallingConvention.Cdecl)]
        public static extern void ansiunicode2(byte[] ptr);
//上面是同一相C++中函數,只不過在C#中被映射到不同的函數而已
string msg2 = "張三zsw";
            ansiunicode(msg2);
            Console.WriteLine("張三zsw的utf8字節長度=" + Encoding.UTF8.GetBytes(msg2).Length);
            byte[] bs = Encoding.UTF8.GetBytes(msg2);
            foreach (byte b in bs)
                Console.Write(b + " ");
            Console.WriteLine("轉換成byte[]之後");
            ansiunicode2(Encoding.UTF8.GetBytes(msg2));
void ansiunicode(char* ptr)
{
	wchar_t* pc = (wchar_t*)ptr;
	int index = 0;
	int len = _tcslen((wchar_t*)ptr);

	int ansilen = strlen(ptr);
	cout << "wchar len=" << len << " ansi len=" << ansilen << endl;

}

wchar len=4 ansi len=7
張三zsw的utf8字節長度=9
229 188 160 228 184 137 122 115 119 轉換成byte[]之後
wchar len=5 ansi len=9

本實驗的現象:同一個c#字符串"張三zsw",直接以string-->char*轉入c++,wcharlen=4而ansilen=7,而在C#中先轉成byte[],再以byte[]-->char*,wcharlen=5,andilen=9。通過我們人眼可看到確實是有5個“字符”,通過轉換出來的byte可知有9個(229 188 160對應字符'張',228 184 137對應字符'三',

122 115 119分別對應z s w,那這麼可以知道將string轉成byte[]之後傳入c++纔是正確的(這麼說只能說是因爲在C++中將字符串當作寬字符來處理是錯誤的,如果用 mbsrtowcs (見使用例子)還有一個例子將多字節unicode轉換成寬字符,則應該與轉成byte[]之後再計算字符數的結果是一樣的).。

總結:

在c#中將字符串傳給C++,如果C++中只是用wchar_t或其指針進行處理,那麼最好在c#中將字符串轉成byte[]。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章