将托管byte []转换为struct []

时间:2014-07-30 06:15:31

标签: c# .net struct casting pinvoke

请考虑以下代码作为在struct []byte []之间复制内存的示例。内存复制的方法与核心问题无关。它在那里演示了两个指向托管数组的指针。

[DllImport("kernel32.dll", EntryPoint = "CopyMemory", SetLastError = false)]
public static extern void CopyMemory (IntPtr dest, IntPtr src, uint count);

public struct MyStruct { public float Value; public TimeSpan Value; }

var bufferSize = 1000000;
var size = Marshal.SizeOf(typeof(MyStruct));
var bufferSource = new MyStruct [bufferSize];
var bufferTarget = new byte [bufferSize * size];

for (int i = 0; i < bufferSource.Length; i++)
{
    bufferSource [j] = new MyStruct() { Value = i; };
}

var handleSource = GCHandle.Alloc(bufferSource, GCHandleType.Pinned);
var handleTarget = GCHandle.Alloc(bufferTarget, GCHandleType.Pinned);
var pointerSource = handleSource.AddrOfPinnedObject();
var pointerTarget = handleTarget.AddrOfPinnedObject();
handleSource.Free();
handleTarget.Free();

CopyMemory(pointerTarget, pointerSource, (uint) (bufferSize * size));

IntPtr pointerTarget并非来自MyStruct []。有没有办法将这个分配和初始化的内存转换为MyStruct []?我不想分配新的数组来做到这一点。

1 个答案:

答案 0 :(得分:1)

重新定义p / invoke签名更容易,在这种情况下如下:

[DllImport("kernel32.dll", EntryPoint = "RtlMoveMemory")]
private static extern void CopyMemory([In, Out] byte[] pdst, Mystruct[] psrc, int cb);

定义p / invoke的结构布局:

[StructLayout(LayoutKind.Sequential)]
public struct MyStruct { public float Value; public TimeSpan Value;}

然后你可以像这样使用它:

CopyMemory(bufferTarget, bufferSource, bufferTarget.Length);