开发者

Marshalling between C# and C++, and the Juggling of Responsibilities

what if I had a native C++ function in which, depending on the result of the function, the responsibility of deleting a certain pointer (delete[]) differs be开发者_如何学Ctween the caller and the function. I would of course check for the return value and act accordingly in C++.

Question is, what if the function was marshalled between C++ and C#, will setting the pointer to null in C# be enough?


No. C# can't do what delete[] in C++ does. You'd have to use a shared memory allocation API, or write a C++ wrapper that handles the cleanup.


No, simply setting a pointer allocated in native code to null will not free the memory. The CLR can only garbage collect memory that it knows about (aka managed memory). It has no idea about native memory and hence can't collect it. Any native memory which has ownership in a managed type must be explicitly freed.

The most common way this is done is via the Alloc and Free functions on the Marshal class

  • http://msdn.microsoft.com/en-us/library/atxe881w.aspx
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜