C#中的结构封送

本文关键字:结构 | 更新日期: 2023-09-27 17:59:49

我在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.

问题出在哪里?提前感谢!

C#中的结构封送

SizeOf不适用于数组。请改用array.Length * Marshal.SizeOf(elementType)

您报告为编译错误的错误实际上是运行时错误(ArgumentException)。如果要使用structtobytecontrol转换为byte[],则应向该方法传递对control的引用,而不是byte数组(byte[])。

control ctrl = new control();
byte[] bytes = structtobyte(ctrl);