c# - C# 中的结构编码(marshal)

标签 c# arrays interop struct marshalling

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

相关文章:

c# - 如何提高循环效率

c# - Cascade.All() EXCEPT Delete 是否有可能?

c# - WPF MVVM : ItemTemplate for binding a list of ICommands to a ListBox

c# - 如何在wpf中延迟调用文本框的textchanged事件

c - 如何编写/构建 C 代码以避免与现有汇编代码冲突?

arrays - jq:只选择一个包含元素 A 但不包含元素 B 的数组

c++ - 在 C++ 中保存和加载大数组

arrays - 数组 SDE 面试问题的恒定空间限制。 AND 对经典面试问题的疑惑

.net - 我自己的托管类型作为 C++/CLI 类库中的 arg : CS0570: is not supported by the language

c# - 如何使用 .NET 4.0 读取 .RTF 文件