我在 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)
。
关于c# - C# 中的结构编码(marshal),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6399332/