Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent garbage collection for managed reference which is used in unmanaged code

My C# application uses wrapped C++ code for calculations.

C++ header:

__declspec(dllexport) void SetVolume(BYTE* data, unsigned int width);

C++/CLI wrapper:

void SetVolume(array<Byte>^ data, UInt32 width) 
{
    cli::pin_ptr<BYTE> pdata = &data[0];
    pal->SetVolume(pdata, width); 
}

C# :

public startCalc()
{
    byte[] voxelArr = File.ReadAllBytes("Filtered.rec");
    palw.SetVolume(voxelArr, 490);
    //GC.KeepAlive(voxelArr); makes no sense
}

The C++ SetVolume function starts asynchronous calculations. voxelArr is not referenced from the managed side any longer and is garbage collected.

How can I prevent the garbage collection for this reference until the unmanaged code finished it's work without to declare voxelArr as global variable? Creating a copy of array isn't an option as there is really a lot of data. Active wait inside of startCalc() isn't good too.

like image 478
VladL Avatar asked Feb 06 '13 17:02

VladL


1 Answers

You can use GCHandle.Alloc(voxelArr,GCHandleType.Pinned) to pin the array manually so the GC won't move or clean it.

You would then have to Free the handle when you knew the method was complete, which would require some form of callback for the completion.

like image 199
Reed Copsey Avatar answered Sep 28 '22 12:09

Reed Copsey