如何将C++结构转换为 C# 等效结构?
How to convert a C++ struct to C# equivalent?
这是我C++结构(文档说每个实例的大小必须正好是 10 个字节(:
#pragma pack (1)
struct LaserPoint {
WORD x;
WORD y;
byte colors[6];
};
我做了以下 C# 结构:
[StructLayout(LayoutKind.Sequential, Pack=1)]
public struct LaserPoint {
public UInt16 x; // 2 bytes
public UInt16 y; // 2 bytes
public byte[] colors; // 6 bytes
}
以下是我在 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();
}
}
}
这是控制台上的输出:
LaserPoint.Size: 8
为什么point
大小为 8 字节而不是 10 字节?
UInt16 = 2 bytes
UInt16 = 2 bytes
byte[6] = 6 bytes
Total = 10 bytes ?
我在这里缺少什么?
[StructLayout(LayoutKind.Sequential, Pack=1)]
public struct LaserPoint {
public UInt16 x; // 2 bytes
public UInt16 y; // 2 bytes
public byte[] colors; // 6 bytes
}
byte[] colors
不是 6 个字节宽。它甚至不是一个实际的数组,而是对堆上字节数组的引用。根据您的平台,它的大小为 32 位(4 字节(或 64 位(8 字节((内部它是一个指针(。这就是为什么您获得 8 字节的大小(2 字节 + 2 字节 + 4 字节(。在 64 位平台上,您将获得 12 字节 (2+2+8( 的大小。
要使struct
的行为像C++struct
添加MarshalAsAttribute
并指定UnmanagedType.ByValArray
和SizeConst
:
[StructLayout(LayoutKind.Sequential, Pack=1)]
public struct LaserPoint {
public UInt16 x;
public UInt16 y;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]
public byte[] colors;
}
我认为问题出在数组上...试试这个:
[StructLayout(LayoutKind.Sequential, Pack=1)]
public struct LaserPoint {
public UInt16 x; // 2 bytes
public UInt16 y; // 2 bytes
[MarhalAs(UnmanagedType.ByValArray, SizeConst = 6]
public byte[] colors; // 6 bytes
}
相关文章:
- 在C++中将结构转换和存储为二进制
- 如何大致将 cpp 代码结构转换为 python
- 如何将可变大小的结构转换为字符数组
- 尝试传递结构数组,但出现"无法将'结构'转换为'结构*'错误
- 我可以安全地将浮点数的结构转换为浮点数组吗C++?
- 如何将结构转换为字符串?
- 如何将C++结构转换为 C# 等效结构?
- 将结构转换为布尔值
- 将具有不同字段的结构转换为 uint8 的数组
- 将 constexpr 结构转换为运行时结构
- 将结构转换为类
- 我必须将记录结构转换为一类,并且不断遇到多个错误
- 如何将 ANSI C 结构转换为 C++ 类,但保持其 ANSI C 友好
- 将 C++ 中的结构转换为 Java 中的类
- 将结构转换为 constexpr 数组uint8_t
- 将大型结构转换为小型C
- c++正在将未知结构转换为字符串
- C++隐式将平凡可构造的结构转换为成员
- 将C++联合结构转换为 VB6
- C到C++:将结构转换为类