[英]passing unicode string from C# exe to C++ DLL
在我的C#exe中使用此函數,我嘗試將Unicode字符串傳遞給我的C ++ DLL:
[DllImport("Test.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
public static extern int xSetTestString(StringBuilder xmlSettings);
這是C ++ DLL端的功能:
__declspec(dllexport)int xSetTestString(char * pSettingsXML);
在C#中調用函數之前,我執行MessageBox.Show(string)並正確顯示所有字符。 在C ++方面,我這樣做:OutputDebugStringW((wchar_t *)pString);,但是這表明非ASCII字符被'?'替換。
只需將本機DLL中的導出更改為:
extern "C" __declspec(dllexport) int xSetTestString(wchar_t* pSettingsXML);
這樣就可以了。
BTW - 你不能簡單地做char* str1 = (wchar_t*)pSettingsXML;
因為它不轉換字符串。 您需要使用wcstombs_s
將wchar_t*
轉換為char*
。 但在你的情況下,你不必這樣做。
注意:最佳實踐IMO是直接使用TCHAR*
而不是wchar_t*
,並將您的本機DLL項目常規選項字符集設置為使用Unicode字符集 。 這將TCHAR*
定義為wchar_t*
。
Mirosoft本身使用兩組函數:ANSI,使用1字節字符,標記為FunctionNameA和Unicode,使用2字節字符,標記為FunctionNameW。 這個Unicode實際上是UTF-16。
UTF-8是一個多字節字符串,對於標准字符使用1字節,對於非標准字符使用2字節。 要將UTF-8轉換為UTF-16,您可以使用MultiByteToWideChar
函數。
嘗試:
[DllImport("Test.dll")]
[return : MarshalAs(UnmanagedType.I4)]
private static extern int externalTestString(
[MarshalAs(UnmanagedType. // The string type the C uses ansi/unicode/...) ] String st
);
public int TestString(String st // or string builder here)
{
// Perform input/output checks here + exception handling
}
確保C ++函數在DLL外部可見(使用__declspec dllexport)。 如果您可以看到函數及其名稱,請使用depends(自帶VS2005)進行檢查。
如果你的C ++函數不在類中,那么你可以使用uncengled名稱,如果你使用extern“C”,如果它們在類中,你需要指定一個帶有來自depends的錯位名稱的入口點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.