LPCSTR
is a pointer to null-terminated array of char
, and UnmanagedType.LPWStr
is a pointer to null-terminated array of wchar_t
. So there is a simple mis-match.
The reason why you only received a single character is that ASCII characters, when represented as two byte UTF-16 characters, have the ASCII value in one byte, and a zero in the other byte. When interpreted as null-terminated array of char
, this is a string of length one. The zero byte is interpreted as the null-terminator.
You can fix it by changing either:
LPCSTR
toLPCWSTR
on the native side, orUnmanagedType.LPWStr
toUnmanagedType.LPStr
on the managed side.
Frankly, to me it makes more sense to use Unicode these days so I would go for option 1. Indeed, since you specified CharSet.Unicode
then there is no need for the MarshalAs
at all. The code would look like this:
C++
BOOL std_call MyCppMethod(LPCWSTR param1, LPCWSTR param2);
C#
[DllImport("MyDll.dll", CharSet = CharSet.Unicode)]
public static extern bool MyCppMethod(string param1, string param2);
Note that I am also sceptical of your setting SetLastError
to true
. Does your function really call SetLastError
?