我的不安全方法接受集合 byte[]
。所有这些 byte[]
的大小都相同。
我需要遍历它们,寻找特定的模式。搜索本质上是重新解释转换样式:在每个偏移量处,我需要将一个值视为 float 、 double 、短整型、整数等。因此获取一个 byte*
每个输入 byte[]
并在每次迭代中递增它似乎是一种自然的方法。
不幸的是,我找不到任何方法来创建 byte*
的集合 - 或者,更具体地说,无法从数组集合中初始化它。有什么想法吗?
这是该任务的一个有点做作的版本:
static unsafe void SearchIteration(List<byte[]> arrays, byte[] resultArr)
{
fixed (byte* resultFix = resultArr)
{
byte* resultPtr = resultFix;
byte*[] pointers = new byte*[arrays.Count];
<some code to fix all the arrays and store the pointers in "pointers">
int remaining = resultArr.Length;
while (remaining > 0)
{
<look at resultPtr and each of the pointers and update *resultPtr>
remaining--;
for (int i = 0; i < pointers.Length; i++)
pointers[i]++;
}
}
}
本质上,问题是如何使用arrays
的地址初始化pointers
,同时固定数组以使 GC 不移动它们。
最佳答案
使用 System.Runtime.InteropServices
中的 GCHandle.Alloc()
:
var handles = new GCHandle[arrays.Count];
byte*[] pointers = new byte*[arrays.Count];
for(int i = 0; i < arrays.Count; ++i)
{
handles[i] = GCHandle.Alloc(arrays[i], GCHandleType.Pinned);
pointers[i] = (byte*)handles[i].AddrOfPinnedObject();
}
try
{
/* process pointers */
}
finally
{
for(int i = 0; i < arrays.Count; ++i)
{
handles[i].Free();
}
}
关于c# - 在 C# 中初始化一个 byte* 的集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3560671/