gpt4 book ai didi

c# - 如何获取 List 中数组的 IntPtr?

转载 作者:太空宇宙 更新时间:2023-11-03 18:04:54 25 4
gpt4 key购买 nike

我正在使用具有函数 SendBuffer(int size, IntPtr pointer) 的库与 IntPtr作为参数。

 var list = new List<float>{3, 2, 1};
IntPtr ptr = list.getPointerToInternalArray();
SendBuffer(ptr, list.Count);

如何获得IntPtr来自存储在 List<T> 中的数组(和/或 T[])?

最佳答案

如果这是对非托管代码的 P/Invoke 调用,您应该检索缓冲区的固定地址(以防止 GC 重新定位缓冲区)并将其传递给方法:

// use an array as a buffer
float[] buffer = new float[]{3, 2, 1};

// pin it to a fixed address:
GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
try
{
// retrieve the address as a pointer and use it to call the native method
SendBuffer(handle.AddrOfPinnedObject(), buffer.Length);
}
finally
{
// free the handle so GC can collect the buffer again
handle.Free();
}

关于c# - 如何获取 List<T> 中数组的 IntPtr?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34962196/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com