Need I free the memory allocated in unmanaged code?

  • Thread starter Thread starter news.microsoft.com
  • Start date Start date
N

news.microsoft.com

In the Pinvoke example, I find the following example:

unmanaged code:

extern "C" PINVOKELIB_API char* TestStringAsResult()
{
char* result = (char*)CoTaskMemAlloc( 64 );
strcpy( result, "This is return value" );
return result;
}

managed code:

public class LibWrap{
[ DllImport( "..\\LIB\\PinvokeLib.dll" )]
public static extern String TestStringAsResult();
}

String str = LibWrap.TestStringAsResult();


the memory is allocated in unmanaged code, need I free the memory allocated
in managed code? if so, how to free it?

thanks in advance!
 
Hi there -

you don't need to work with memory allocations. The Platform Invocation
Services will make the call and after that will marshal the data for you.
That means that when you assign the result to your local variable, you'll
actually have a managed copy of it (in this case the string).

There are sometimes in which you need to pass a pointer to an ouput variable
(char*) when you shouldn't work with string type directly, but pass a
reference to a StringBuilder. Then after the call you can convert the
StringBuilder to a string, but that's only when a call to a low-level API is
needed.

There is an interesting article on the subject on the MSDN online (by Eric
Gunnerson), available at
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dncscol/html/csharp12192002.asp.

Cheers,
Branimir
 
Back
Top