Consider the following code as an example of copying memory between a struct []
and a byte []
. The method of memory copy is irrelevant to the core question. It's there to demonstrate two pointers to managed arrays.
[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));
The IntPtr pointerTarget
did not originate as a MyStruct []
. Is there a way to cast this allocated and initialized memory to a MyStruct []
? I do not want to allocate a new array to be able to do this.