3 个版本 (破坏性更新)
0.3.0 | 2023年6月29日 |
---|---|
0.2.0 | 2023年6月29日 |
0.1.0 | 2023年4月26日 |
#419 在 内存管理
6KB
memory-layout
memory-layout
是一个最小的 no_std
兼容包,允许您指定结构体的内存布局,类似于 C# 的 [StructLayout(LayoutKind.Explicit)]
。
文档
https://docs.rs/memory-layout/
特性
- 指定结构体字段应具有的偏移量。
- 偏移量在编译时进行检查以确保有效。
no_std
兼容。
示例
use memory_layout::memory_layout;
#[memory_layout]
pub struct Example {
#[field_offset(0x00)]
a: i32,
#[field_offset(0x10)]
b: u64,
#[field_offset(0x20)]
c: f32
}
将扩展为
pub struct Example {
#[doc(hidden)]
__pad0: [u8; 0usize],
a: i32,
#[doc(hidden)]
__pad1: [u8; 16usize - ::core::mem::size_of::<i32>()],
b: u64,
#[doc(hidden)]
__pad2: [u8; 8usize - ::core::mem::size_of::<u64>()],
c: f32
}
注意事项
- 字段必须按指定偏移量升序定义。
#[memory_layout]
属性必须在任何derive
属性之前定义。
可比项目
struct_layout
此项目与该包有类似的目标,复制 C# 的 [StructLayout(LayoutKind.Explicit)]
。主要区别在于,struct_layout
使用一个内部数组,可以通过诸如 get_<field_name>
和 set_<field_name>
等方法访问,而此包则对齐字段本身。
依赖项
~3MB
~57K SLoC