如何将C++结构转换为C#等价?

sal*_*inx 2 c# c++ dll interop dllimport

这是我的C++结构(文档说每个实例的大小必须是10个字节):

#pragma pack (1)
struct LaserPoint {
    WORD x;
    WORD y;
    byte colors[6];
};
Run Code Online (Sandbox Code Playgroud)

我做了以下C#结构:

[StructLayout(LayoutKind.Sequential, Pack=1)]
public struct LaserPoint {
    public UInt16 x;                   // 2 bytes
    public UInt16 y;                   // 2 bytes
    public byte[] colors;              // 6 bytes
}
Run Code Online (Sandbox Code Playgroud)

这是我的C#项目中的完整测试代码:

using System;
using System.Runtime.InteropServices;

namespace StructSizeTest {
    class Program {

        [StructLayout(LayoutKind.Sequential, Pack=1)]
        public struct LaserPoint {
            public UInt16 x;                   // 2 bytes
            public UInt16 y;                   // 2 bytes
            public byte[] colors;              // byte[6] = 6 bytes
        }

        static void Main(string[] args) {

            LaserPoint point = new LaserPoint();
            point.x = (UInt16)16384;
            point.y = (UInt16)32768;
            point.colors = new byte[6];
            point.colors[0] = 255;
            point.colors[1] = 255;
            point.colors[2] = 255;
            point.colors[3] = 255;
            point.colors[4] = 255;
            point.colors[5] = 255;

            Console.WriteLine("LaserPoint.Size: " + Marshal.SizeOf(point));

            Console.ReadLine();
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

这是控制台上的输出:

LaserPoint.Size: 8
Run Code Online (Sandbox Code Playgroud)

为什么point8个字节大小而不是10个字节?

UInt16  = 2 bytes
UInt16  = 2 bytes
byte[6] = 6 bytes
Total   = 10 bytes ?
Run Code Online (Sandbox Code Playgroud)

我在这里缺少什么?

Adr*_*ian 5

[StructLayout(LayoutKind.Sequential, Pack=1)]
public struct LaserPoint {
    public UInt16 x;                   // 2 bytes
    public UInt16 y;                   // 2 bytes
    public byte[] colors;              // 6 bytes
}
Run Code Online (Sandbox Code Playgroud)

byte[] colors不是6个字节宽.它甚至不是一个实际的数组,而是对堆上字节数组的引用.根据您的平台,它具有32位(4字节)或64位(8字节)的大小(内部,它是一个指针).这就是为什么你得到一个8字节的大小(2字节+2字节+4字节).在64位平台上,您将获得12字节(2 + 2 + 8)的大小.

struct像C++一样struct添加MarshalAsAttribute并指定UnmanagedType.ByValArraySizeConst:

[StructLayout(LayoutKind.Sequential, Pack=1)]
public struct LaserPoint {
    public UInt16 x;                  
    public UInt16 y;                         
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]
    public byte[] colors;             
}
Run Code Online (Sandbox Code Playgroud)