How do I marshal a .net string to a null terminated ascii or utf8 IntPtr. For use on linux when interloping to a c lib.
I'm trying to call a c function with signiture like the following:
void my_function(const char* str)
My c# definition is as follows:
[DllImport("mylib.so)]
public static extern void my_function(IntPtr str);
I'm using an IntPtr for the interop because the native code holds onto the string longer than the duration of the function call. So I need to be able to marshal/pin it myself.
Things I've considered:
- Marshal.StringToHGlobalUni (seems to do 16 bit characters)
- Marshal.StringToHGlobalAnsi (ansi is for windows I think)
- Marshal.StringToCoTaskMemUTF8 (says it uses the Com allocator, which seems wrong as this is not for com interop)
- Marshal.StringToBSTR (says it's for com interop)
- Marshal.StringToHGlobalAuto (not sure about this one, says it converts to ansi if required which isn't what I want, also no details on how it decides or what it converts to if it doesn't do ansi)
There is also the option of converting to a ascii or utf8 byte array and then marshalling the resulting array (with a null terminator on the end) but this seem like overkill, especially if one of the string marshalling options does the correct thing.