如何将指定大小的C++结构体转换为等效的C#结构体?
Fixing C# Struct Size to Match 10-Byte C++ Struct
The issue with your current C# struct is that byte[] colors is a reference type—instead of storing the 6 bytes directly inline in the struct, it stores a pointer to an array (which is 4 or 8 bytes depending on your platform). That's why your struct isn't matching the 10-byte size of the C++ version.
To fix this, you need to use a fixed-size buffer to embed the 6 bytes directly in the struct. Here's the corrected C# code:
using System; using System.Runtime.InteropServices; namespace StructSizeTest { [StructLayout(LayoutKind.Sequential, Pack = 1)] public unsafe struct LaserPoint { public UInt16 x; // 2 bytes public UInt16 y; // 2 bytes public fixed byte colors[6]; // 6 bytes (inline, not a reference) } class Program { static void Main(string[] args) { // Verify the struct size int managedSize = sizeof(LaserPoint); // Requires unsafe context int marshaledSize = Marshal.SizeOf(typeof(LaserPoint)); Console.WriteLine($"Managed struct size: {managedSize} bytes"); Console.WriteLine($"Marshaled struct size: {marshaledSize} bytes"); // Both should output 10 } } }
Key Details:
- You need to enable unsafe code in your project settings (right-click project → Properties → Build → Check "Allow unsafe code").
- The
fixedkeyword forces the array to be allocated directly within the struct, eliminating the reference pointer overhead. sizeof(LaserPoint)(in unsafe context) gives the exact size of the managed struct, whileMarshal.SizeOfreturns the size when marshaled to unmanaged code—both will be 10 bytes here.
If you want to avoid unsafe code entirely, you can declare 6 separate byte fields (e.g., public byte c1, c2, c3, c4, c5, c6;), though this is less convenient than using a fixed-size buffer.
内容的提问来源于stack exchange,提问作者salocinx
相关产品推荐
相关产品推荐

