防止垃圾收集管理参考这是在非托管代码中使用 [英] Prevent garbage collection for managed reference which is used in unmanaged code

查看:154
本文介绍了防止垃圾收集管理参考这是在非托管代码中使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的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.

推荐答案

您可以使用 GCHandle.Alloc (voxelArr, GCHandleType。固定 手动针阵列使GC将不会移动或清洁。

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.

这篇关于防止垃圾收集管理参考这是在非托管代码中使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆