You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将指定大小的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 fixed keyword 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, while Marshal.SizeOf returns 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:18:56