Passing unicode string from C # exe to C ++ DLL

Using this function in my C # exe, I am trying to pass a Unicode string to my C ++ DLL:

    [DllImport("Test.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
    public static extern int xSetTestString(StringBuilder xmlSettings);

This is a function on the C ++ library side:

__ declspec (dllexport) int xSetTestString (char * pSettingsXML);

Before calling the function in C #, I create a MessageBox.Show (string) and display all characters properly. On the C ++ side, I do: OutputDebugStringW ((wchar_t *) pString); but this shows that non-ASCII characters have been replaced with "?".

+3
source share
2 answers

Just change the export to your native DLL:

extern "C" __declspec(dllexport) int xSetTestString(wchar_t* pSettingsXML);

This will do the trick.

BTW - char* str1 = (wchar_t*)pSettingsXML;, . wchar_t* char* wcstombs_s. .

: IMO , TCHAR* wchar_t* dll. Character Set - Unicode. TCHAR* wchar_t*.

Mirosoft : ANSI, 1- , FunctionNameA Unicode, 2- , FunctionNameW. UTF-16.

UTF-8 - , 1- 2 . UTF-8 UTF-16 MultiByteToWideChar.

+5

Try:

[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
}

, ++ DLL ( ​​ __declspec dllexport). ( VS2005), .

++ , unmangled names, extern "C", , .

0

Source: https://habr.com/ru/post/1749688/


All Articles