Orca
Orca

Reputation: 2025

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 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?

Upvotes: 1

Views: 195

Answers (2)

JaredPar
JaredPar

Reputation: 755587

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

Upvotes: 0

Mattias S
Mattias S

Reputation: 4808

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.

Upvotes: 3

Related Questions