views:

34

answers:

2

Hello everybody, 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 between 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?

+3  A: 

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.

Mattias S
What about making the object = null? Wouldn't that let the ever trustworthy garbage man collect its memory as unused?
Voulnet
You mean the CLR garbage collector? No, it doesn't know about memory allocated in native C++ code.
Mattias S
What if the type was marshalled as an IntPtr?
Voulnet
Then you'd still need some memory deallocation function to call to free the memory the IntPtr points to. Whether it's one of the Windows memory allocation functions or on in your C++ library that calls delete[].
Mattias S
A: 

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

JaredPar
What if the type was not marshalled as an IntPtr?
Voulnet
@Voulnet, that's a bug then. If the code is a memory address and was not marashal'd as an `IntPtr` it will not work in 64 bit processes
JaredPar