Struct marshal in C#

故事扮演 提交于 2019-12-04 12:07:25

问题


I have the following struct in 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];
    }

And the function i use to convert it to byte array[] is

 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;
    }

When i compile it gives

Type 'System.Byte[]' cannot be marshaled as an unmanaged structure; no meaningful size or offset can be computed.

What can be the problem? Thanks in advance!


回答1:


SizeOf doesn't work on arrays. Use array.Length * Marshal.SizeOf(elementType) instead.




回答2:


The error you are reporting as a compile error is in fact a runtime error (an ArgumentException). When you want to use structtobyte to convert a control to byte[] you should pass the method a reference to control, not a byte array (byte[]).

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


来源:https://stackoverflow.com/questions/6399332/struct-marshal-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!