MrNick
MrNick

Reputation: 399

C# P/Invoke [DllImport] - array memory management

I'm passing a byte[] to a function accepting an unsigned char*

One way I can do this is to pass an IntPtr, and allocate/deallocate memory in managed code as follows:

I can also do this:

Both implemntations work well, but in my second example, how is the memory (for the unsigned char* message) managed. I'm guessing that memory is allocated when the call to Foo is made, and deallocated when it returns (so it behaves much like the first example) - is this correct?

Thanks

Upvotes: 3

Views: 3580

Answers (1)

weismat
weismat

Reputation: 7411

There is no management done in the second case. The GC does not count references done from unmanaged code. This is fine when the external function does not work with threads or uses the reference at a later function call.
There is a similar issue when you are working with delegates/function pointers and unmanaged code, where it can happen to you that the delegate gets dealloacted at a random point. This MSDN article is great to explain you all the details.

Upvotes: 2

Related Questions