ubaabd ubaabd - 2 months ago 8
C# Question

Garbage Collection in C++/CLI, C# Mixed Code

I am passing an array by reference from C# to C++/CLI to use as an out parameter. My code is as follows:


ushort[] a = new ushort[1];
cppclr.method(ref a);


void method(array<ushort>^% a)
a = gcnew array<ushort>(5);
a[0] = 1;
a[1] = 2;
a[2] = 3;

The code compiles fine and produces no error. However, I am confused whether the array that I created in C# has been taken care of by the garbage collection? My confusion is that since I am assigning a new memory inside C++/CLI, the previous reference is lost and should be handled by garbage collection. The program doesn't show any memory leaks. Do I need to take care of this situation in any other way?


Everything is being taken care of. Whether you're running C# or C++/CLI or any other .NET language for that matter, it's the same runtime that executes both under the hood. Therefore you get the same GC for both.

As you used gcnew, you used the runtime's managed memory allocator. Had you used new with an unmanaged array in C++/CLI, you'd have to free it with the delete[] operator afterwards.