是否有与 C# Structs/StructLayout 等效的功能,C++中的字段偏移量?
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);
相关文章:
- 在执行其他功能的同时播放动画(LED矩阵和Arduino/ESP8266)
- 多态性和功能结合
- 带内存和隔离功能的SQLite
- 在CMakeLists.txt的安装功能中使用.cmake文件有什么用
- 类模板的成员功能的定义在单独的TU中完全专业化
- 有没有一种方法可以创建一个带有哈希表的数据库,该哈希表具有恒定时间查找功能
- 如何在C++中获得"静态纯虚拟"功能?
- 两个文件使用彼此的功能-如何解决
- 我应该实现右值推送功能吗?我应该使用std::move吗
- QML按钮点击功能执行顺序
- 无法理解此 return 语句的功能,没有它就会发生运行时错误
- 有没有可能有一个只有ADL才能找到的非好友功能
- 功能样式转换从 'int' 到 'ItemType' 的匹配转换
- 文件系统:复制功能的速度秘诀是什么
- 在用于格式4的arm模拟器中实现功能时的一个问题
- 如何在Directwrite中获得给定字体的可用OpenType功能
- 对可变参数使用声明.如何选择正确的功能
- 询问在设计我的手臂模拟器功能表示格式1
- 功能原型的目的
- 这里在 Linux 中具有"CreatePipe"和"CreateProcessW"功能吗?