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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With