问题描述
我的C#应用程序使用封装的C ++代码进行计算。
My C# application uses wrapped C++ code for calculations.
C ++头:
__declspec(dllexport) void SetVolume(BYTE* data, unsigned int width);
C ++ / CLI包装:
C++/CLI wrapper:
void SetVolume(array<Byte>^ data, UInt32 width)
{
cli::pin_ptr<BYTE> pdata = &data[0];
pal->SetVolume(pdata, width);
}
C#:
C# :
public startCalc()
{
byte[] voxelArr = File.ReadAllBytes("Filtered.rec");
palw.SetVolume(voxelArr, 490);
//GC.KeepAlive(voxelArr); makes no sense
}
的
C ++ SetVolume
函数开始的同步的计算。 voxelArr
不从管理方引用的任何时间更长,是垃圾收集。
The C++ SetVolume
function starts asynchronous calculations. voxelArr
is not referenced from the managed side any longer and is garbage collected.
如何防止垃圾收集此引用,直到非托管代码完成它的工作,但无申报 voxelArr
作为全局变量?创建数组的一个副本是不是真的有很多数据的选项。活动等在内startCalc()的是不好过。
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.
推荐答案
您可以使用
(voxelArr,
)
手动针阵列使GC将不会移动或清洁。
You can use
GCHandle.Alloc
(voxelArr,
GCHandleType.Pinned
)
to pin the array manually so the GC won't move or clean it.
然后你将不得不免费当你知道这个方法是完全的,这需要某种形式的回调完成的句柄。
这篇关于防止垃圾收集管理参考这是在非托管代码中使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!