[英]Struct marshal in C#
我在C#中有以下結構
unsafe public struct control
{
public int bSetComPort;
public int iComPortIndex;
public int iBaudRate;
public int iManufactoryID;
public byte btAddressOfCamera;
public int iCameraParam;
public byte PresetNum;
public byte PresetWaitTime;
public byte Group;
public byte AutoCruiseStatus;
public byte Channel;
public fixed byte Data[64];
}
我用來將它轉換為字節數組[]的函數是
static byte[] structtobyte(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;
}
當我編譯它給
Type 'System.Byte[]' cannot be marshaled as an unmanaged structure; no meaningful size or offset can be computed.
可能是什么問題? 提前致謝!
SizeOf
不適用於數組。 請改用array.Length * Marshal.SizeOf(elementType)
。
您報告為編譯錯誤的錯誤實際上是運行時錯誤( ArgumentException
)。 如果要使用structtobyte
將control
轉換為byte[]
,則應該將方法傳遞給control
,而不是byte
數組( byte[]
)。
control ctrl = new control();
byte[] bytes = structtobyte(ctrl);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.