Return string from Interop function

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?

@ andre.marschalek - This is about Interop not RLP

@ jay If you don’t have it yet get the source code of the porting kit and check inside \Product\Sample\InteropSample\InteropNativeCode.

There is TestBasicTypes which has GetVersion method. GetVersion should show you haw to interop the strings.


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);
var str = s.ToString();

@ Reinhard Ostermeier

Hmm… I don’t think StringBuilder is supported in NETMF Interop. Do you have an example?

@ Architect - I actually don’t know. I didn’t know that there is interop in NETMF at all, so I assumed it’s on PC side. Sorry, my fault.

No worries. I thought I missed something :slight_smile:

The interop engine will make a copy of the LPCSTR return.
This is simple an safe to return constant string like this

LPCSTR TestBasicTypes::GetVersion( HRESULT &hr )
	LPCSTR retVal = "Interop Version 1.0"; 
	return retVal;

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.