是否有与 C# Structs/StructLayout 等效的功能,C++中的字段偏移量?

Is there equivalent functionality to C# Structs/StructLayout with field offsets in C++?

本文关键字:功能 C++ 字段 偏移量 Structs StructLayout 是否      更新时间:2023-10-16

以这个 C# 结构为例:

[StructLayout(LayoutKind.Explicit)]
public struct Example
{
[FieldOffset(0x10)]
public IntPtr examplePtr;
[FieldOffset(0x18)]
public IntPtr examplePtr2;
[FieldOffset(0x54)]
public int exampleInt;
}

我可以获取一个字节数组,并将其转换为此结构,如下所示:

public static T GetStructure<T>(byte[] bytes)
{
var handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
var structure = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
handle.Free();
return structure;
}
public static T GetStructure<T>(byte[] bytes, int index)
{
var size = Marshal.SizeOf(typeof(T));
var tmp = new byte[size];
Array.Copy(bytes, index, tmp, 0, size);
return GetStructure<T>(tmp);
}
GetStructure<Example>(arrayOfBytes);

C++中是否有等效的功能来获取字节数组并将其转换为结构,其中并非所有字节都用于转换(C# structlayout.explicit w/字段偏移量(?

不想做类似的事情:

struct {
pad_bytes[0x10];
DWORD64 = examplePtr;
DWORD64 = examplePtr2;
pad_bytes2[0x44];
int exampleInt;
}

不,我不知道指定某些结构成员的字节偏移量的方法 - 标准中绝对没有任何内容,而且我不知道任何编译器特定的扩展。

除了填充成员(如前所述(,还可以使用alignas#pragma pack__declspec(align(#))(在 MSVC 上(以及__attribute__ ((packed))__attribute__ ((aligned(#)))(在 GCC 上(。当然,这些不允许您指定偏移量,但它们可以帮助控制结构的布局。

为了确保您的布局符合您的期望,我能想到的最好的方法是将static_assertoffsetof一起使用:

struct Example{
char pad_bytes[0x10];
DWORD64 examplePtr;
DWORD64 examplePtr2;
char pad_bytes2[0x44];
int exampleInt;
};
static_assert(offsetof(Example, examplePtr) == 0x10);
static_assert(offsetof(Example, examplePtr2) == 0x18);
static_assert(offsetof(Example, exampleInt) == 0x54);