这是分配和释放传递给非托管dll的托管数据的句柄的正确方法吗?
存在具有导出功能的非托管dll
void Function(byte** ppData, int N);
我需要传递它IEnumerable<byte[]> afids
var handles = afids.Select(afid => GCHandle.Alloc(afid, GCHandleType.Pinned));
var ptrs = handles.Select(h => h.AddrOfPinnedObject());
IntPtr[] afidPtrs = ptrs.ToArray();
uint N = (uint)afidPtrs.Length;
Function(afidPtrs, N);
handles.ToList().ForEach(h => h.Free());
我得到托管内存泄漏并在立即窗口中获取sos.dll给了gcroot
DOMAIN(00275030):HANDLE(Pinned):3ea2c0:Root: 17a8d190(System.Byte[])
功能定义是:
[DllImport("My.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
static extern unsafe internal int Function(IntPtr[] ppData, int N);
控制台应用程序的Buggy代码段:
static void Main(string[] args)
{
while (!Console.KeyAvailable)
{
IEnumerable<byte[]> data = CreateEnumeration(100);
PinEntries(data);
Thread.Sleep(900);
Console.Write(String.Format("gc mem: {0}\r", GC.GetTotalMemory(true)));
}
}
static IEnumerable<byte[]> CreateEnumeration(int size)
{
Random random = new Random();
IList<byte[]> data = new List<byte[]>();
for (int i = 0; i < size; i++)
{
byte[] vector = new byte[12345];
random.NextBytes(vector);
data.Add(vector);
}
return data;
}
static void PinEntries(IEnumerable<byte[]> data)
{
var handles = data.Select(d => GCHandle.Alloc(d, GCHandleType.Pinned));
var ptrs = handles.Select(h => h.AddrOfPinnedObject());
IntPtr[] dataPtrs = ptrs.ToArray();
Thread.Sleep(100); // unmanaged function call taking byte** data
handles.ToList().ForEach(h => h.Free());
}
正确的控制台应用程序代码段:
static void PinEntries(IEnumerable<byte[]> data)
{
IEnumerable<GCHandle> handles = CreateHandles(data);
IntPtr[] ptrs = GetAddrOfPinnedObjects(handles);
Thread.Sleep(100); // unmanaged function call taking byte** data
FreeHandles(handles);
}
static IEnumerable<GCHandle> CreateHandles(IEnumerable<byte[]> data)
{
IList<GCHandle> handles = new List<GCHandle>();
foreach (byte[] vector in data)
{
GCHandle handle = GCHandle.Alloc(vector, GCHandleType.Pinned);
handles.Add(handle);
}
return handles;
}
static IntPtr[] GetAddrOfPinnedObjects(IEnumerable<GCHandle> handles)
{
IntPtr[] ptrs = new IntPtr[handles.Count()];
for (int i = 0; i < ptrs.Length; i++)
ptrs[i] = handles.ElementAt(i).AddrOfPinnedObject();
return ptrs;
}
static void FreeHandles(IEnumerable<GCHandle> handles)
{
foreach (GCHandle handle in handles)
handle.Free();
}
答案 0 :(得分:3)
static void PinEntries(IEnumerable<byte[]> data)
{
var handles = data.Select(d => GCHandle.Alloc(d, GCHandleType.Pinned));
var ptrs = handles.Select(h => h.AddrOfPinnedObject());
IntPtr[] dataPtrs = ptrs.ToArray();
Thread.Sleep(100); // unmanaged function call taking byte** data
handles.ToList().ForEach(h => h.Free());
}
你陷入了一个Linq陷阱,它的枚举器不像一个集合。当您使用handle.ToList()时,第一次使用ptrs.ToArray()时,句柄将被分配两次。由于明显的副作用,第一组句柄不会被释放。修正:
var handles = data.Select(d => GCHandle.Alloc(d, GCHandleType.Pinned)).ToList();
var ptrs = handles.Select(h => h.AddrOfPinnedObject());
IntPtr[] dataPtrs = ptrs.ToArray();
handles.ForEach(h => h.Free());
注意添加的ToList()强制枚举进入集合。