[英]Initialize a collection of byte* in C#
My unsafe method accepts a collection byte[]
s. 我的不安全方法接受一个集合
byte[]
s。 All of these byte[]
s are of the same size. 所有这些
byte[]
都具有相同的大小。
I need to iterate over them all, searching for certain patterns. 我需要迭代它们,搜索某些模式。 The search is inherently reinterpret-cast style: at each offset, I need to consider a value as if it were a float, a double, a short, an int, etc. So getting a
byte*
for each input byte[]
and incrementing it on each iteration seems like a natural approach. 搜索本质上是重新解释的样式:在每个偏移处,我需要考虑一个值,就好像它是一个浮点数,一个double,一个short,一个int等。所以为每个输入
byte[]
获取一个byte*
并递增它在每次迭代时看起来都是一种自然的方法。
Unfortunately I can't find any way to create a collection of byte*
- or, more specifically, to initialize it from a collection of arrays. 不幸的是,我找不到任何方法来创建
byte*
的集合 - 或者更具体地说,是从一组数组中初始化它。 Any ideas? 有任何想法吗?
Here's a somewhat contrived version of the task: 这是一个有点人为的任务版本:
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]++;
}
}
}
Essentially the question is how to initialize pointers
with the addresses of arrays
, while pinning the arrays so that GC doesn't move them. 本质上问题是如何使用
arrays
的地址初始化pointers
,同时固定数组以便GC不移动它们。
use GCHandle.Alloc()
from System.Runtime.InteropServices
: 使用
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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.