Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

C#

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

C++/CLI

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?

like image 313
ubaabd Avatar asked Dec 05 '25 06:12

ubaabd


1 Answers

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.

like image 157
Lucas Trzesniewski Avatar answered Dec 08 '25 17:12

Lucas Trzesniewski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!