I have an external DLL that returns an AnsiString.
I have set my code up like so:
[DllImport("CDCrypt.dll", CharSet = CharSet.Ansi)]
public static extern string Decrypt(string s);
public string myDllMessage()
{
return DllMessage("Û(ÉÄ´-zÕ< tÆ");
}
Is the cast from AnsiString to String ok with the external dll reference?
Functions that returns strings are a memory management problem. Somebody is going to have to release the memory for the string. The pinvoke marshaller will try to take care of that, it uses CoTaskMemFree().
This is not very likely to work out in practice, native code rarely uses CoTaskMemAlloc() to allocate the memory of the string. On XP this produces an unpluggable memory leak, on Vista and Win7 it will crash your program. They have a much stricter heap manager.
The only thing you can do is declare the return type as IntPtr. Then marshal the return value yourself with Marshal.PtrToStringAnsi(). That will surely work, the odds that you’ll get the proper value back are quite small. The string will be converted from Unicode to Ansi, that’s a lossy conversion. Then you have to release the memory. You can’t. You cannot pinvoke this function.