[英]How to marshal a struct into a UInt16 Array
I know that you can use code like this to marshal a structure into a byte array: 我知道您可以使用如下代码将结构编组为字节数组:
public static byte[] StructureToByteArray(object obj)
{
int len = Marshal.SizeOf(obj);
byte[] arr = new byte[len];
IntPtr ptr = Marshal.AllocHGlobal(len);
Marshal.StructureToPtr(obj, ptr, true);
Marshal.Copy(ptr, arr, 0, len);
Marshal.FreeHGlobal(ptr);
return arr;
}
But how do you marshal a structure into an array containing 16 bit words instead of bytes? 但是,如何将结构编组为包含16位字而不是字节的数组?
public static UInt16[] StructureToUInt16Array(object obj)
{
// What to do?
}
The Unsafe and the Safe way to do this: 执行此操作的不安全和安全方法:
static UInt16[] MarshalUInt16(Object obj)
{
int len = Marshal.SizeOf(obj);
IntPtr ptr = Marshal.AllocHGlobal(len);
Marshal.StructureToPtr(obj, ptr, true);
UInt16[] arr = new UInt16[len / 2];
unsafe
{
UInt16* csharpPtr = (UInt16*)ptr;
for (Int32 i = 0; i < arr.Length; i++)
{
arr[i] = csharpPtr[i];
}
}
Marshal.FreeHGlobal(ptr);
return arr;
}
static UInt16[] SafeMarshalUInt16(Object obj)
{
int len = Marshal.SizeOf(obj);
byte[] buf = new byte[len];
IntPtr ptr = Marshal.AllocHGlobal(len);
Marshal.StructureToPtr(obj, ptr, true);
Marshal.Copy(ptr, buf, 0, len);
Marshal.FreeHGlobal(ptr);
UInt16[] arr = new UInt16[len / 2];
//for (Int32 i = 0; i < arr.Length; i++)
//{
// arr[i] = BitConverter.ToUInt16(buf, i * 2);
//}
Buffer.BlockCopy(buf, 0, arr, 0, len);
return arr;
}
Updated to reflect the wisdom of others. 更新以反映他人的智慧。
Any reason not to marshal into a byte array and then use Buffer.BlockCopy
? 有什么理由不
Buffer.BlockCopy
字节数组中,然后使用Buffer.BlockCopy
吗? That would be the simplest approach, I'd say. 我会说,那将是最简单的方法。 Admittedly you do have to do appropriate copying, so it's less efficient, but I don't think you'll find a much simpler way.
诚然,您必须进行适当的复制,因此效率较低,但是我认为您不会找到更简单的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.