I think, the problem is with the LPWStr
:
you cannot use the LPWStr value with an unmanaged string unless the
string was created by using the unmanaged CoTaskMemAlloc function
This works fine. Native code:
// header
extern "C" __declspec(dllexport) wchar_t* SysGetLibInfo(void);
// implementation
extern "C" __declspec(dllexport) wchar_t* SysGetLibInfo(void)
{
return TEXT("Hello from unmanaged world!");
}
Managed code:
[DllImport("NativeLibrary.dll", CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.LPTStr)]
static extern string SysGetLibInfo();
If you'll change native function this way:
extern "C" __declspec(dllexport) wchar_t* SysGetLibInfo(void)
{
wchar_t* pStr = (wchar_t*)CoTaskMemAlloc(100);
ZeroMemory(pStr, 100);
wcscpy(pStr, TEXT("Hello from unmanaged world!"));
return pStr;
}
then [return: MarshalAs(UnmanagedType.LPWStr)]
will work too.