[英]Is there equivalent functionality to C# Structs/StructLayout with field offsets in C++?
以 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_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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.