I need to return a string from an interop function. Visual Studio stubs out the function with a return type of LPCSTR, which is a typedef for a const char *.
That seems extremely odd – doesn’t the memory I allocate for that string get freed once it returns?
I thought instead I’d pass a string ref into the function as an argument, but string refs aren’t a supported interop type.
How the heck do native functions return strings, then?
For interop you can use the StringBuilder class in combination with the correct MarsahAs attribute in the method declaration.
If the caller must aquire the buffer (which is usually required) simply initialize StringBuilder with a buffer length.
var s = new StringBuilder(128);
InteropCall(s);
var str = s.ToString();
The memory handling is no so easy if you allocate the string. The LPCSTR will not be deleted by the CLR and obviously you can’t delete it before return!
This memory must be deleted in another function. Fortunately, Dispose() is made for that.
Declare a static LPCSTR pointer that will be use either by your method and your native Dispose() method.
If your method is called more than once, the previous string has be deleted before the next creation.
Another method is to use a static buffer. No allocation needed but the memory is used even if the feature is not called.