gpt4 book ai didi

c# - 在 C++ 中是否有与 C# Structs/StructLayout 具有字段偏移的等效功能?

转载 作者:行者123 更新时间:2023-12-01 13:47:55 26 4
gpt4 key购买 nike

以 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/field offsets)?

不要想做如下事情:
struct {
pad_bytes[0x10];
DWORD64 = examplePtr;
DWORD64 = examplePtr2;
pad_bytes2[0x44];
int exampleInt;
}

最佳答案

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

除了填充成员(正如您已经提到的),您还可以使用 alignas , #pragma pack , 和 __declspec(align(#)) (在 MSVC 上)和 __attribute__ ((packed)) __attribute__ ((aligned(#))) (在海湾合作委员会上)。当然,这些不允许您指定偏移量,但它们可以帮助控制结构的布局。

我能想到的最好的方法是使用 static_assert 来确保您的布局符合您的期望。与 offsetof :

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);

关于c# - 在 C++ 中是否有与 C# Structs/StructLayout 具有字段偏移的等效功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61833216/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com