C# 中的结构元帅

发布于 2024-11-16 06:13:19 字数 1039 浏览 8 评论 0原文

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

问题是什么? 提前致谢!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

花心好男孩 2024-11-23 06:13:19

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

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

渡你暖光 2024-11-23 06:13:19

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

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

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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文