O
O.B.
I have operation within a class that marshals the data into a byte
array. Below are three different ways that work. Are there any
downsides to using one over the the other?
public virtual byte[] ToRaw1()
{
byte[] byteArray = new byte[Size];
IntPtr pointer = Marshal.AllocHGlobal(Size);
Marshal.StructureToPtr(this, pointer, false);
Marshal.Copy(pointer, byteArray, 0, Size);
Marshal.FreeHGlobal(pointer);
return byteArray;
}
public virtual byte[] ToRaw2()
{
byte[] byteArray = new byte[Size];
IntPtr byteArrayPtr = Marshal.UnsafeAddrOfPinnedArrayElement
(byteArray, 0);
Marshal.StructureToPtr(this, byteArrayPtr, false);
return byteArray;
}
public virtual byte[] ToRaw3()
{
byte[] byteArray = new byte[Size];
unsafe
{
fixed (byte* pData = byteArray)
{
Marshal.StructureToPtr(this, (IntPtr)pData, false);
}
}
return byteArray;
}
array. Below are three different ways that work. Are there any
downsides to using one over the the other?
public virtual byte[] ToRaw1()
{
byte[] byteArray = new byte[Size];
IntPtr pointer = Marshal.AllocHGlobal(Size);
Marshal.StructureToPtr(this, pointer, false);
Marshal.Copy(pointer, byteArray, 0, Size);
Marshal.FreeHGlobal(pointer);
return byteArray;
}
public virtual byte[] ToRaw2()
{
byte[] byteArray = new byte[Size];
IntPtr byteArrayPtr = Marshal.UnsafeAddrOfPinnedArrayElement
(byteArray, 0);
Marshal.StructureToPtr(this, byteArrayPtr, false);
return byteArray;
}
public virtual byte[] ToRaw3()
{
byte[] byteArray = new byte[Size];
unsafe
{
fixed (byte* pData = byteArray)
{
Marshal.StructureToPtr(this, (IntPtr)pData, false);
}
}
return byteArray;
}