Crates.io | hun-offsetof |
lib.rs | hun-offsetof |
version | 0.1.1 |
source | src |
created_at | 2023-01-31 12:25:00.746334 |
updated_at | 2023-04-17 09:09:43.703802 |
description | Provides C-like macros: offset_of and container_of |
homepage | |
repository | https://gitee.com/1467792822/roffsetof |
max_upload_size | |
id | 772653 |
size | 18,333 |
Provides C-like macros: offset_of and container_of
基于指针的操作属于unsafe范围,如果使用声明宏方式,可能出现嵌套unsafe的编译告 警,而过程宏可以消除这类告警。 Pointer-based operations are unsafe, If the declaration macro mode is used, nested unsafe compilation warnings may be generated, which can be eliminated by procedure macro.
offset_of!(type, member) -> usize;
container_of!(&obj, type, member) -> &type;
container_of_mut!(&obj, type, member) -> &mut type;
extern crate hun_offsetof as hun;
#[repr(C)]
struct Bar {
key: i32,
value: i32,
}
#[repr(C)]
struct Foo {
key: i32,
value: [Bar; 2],
}
assert_eq!(hun::offset_of!(Bar, value), 4);
assert_eq!(hun::offset_of!(Foo, value[1].key), 12);
let foo = Foo {
key: 1,
value: [ Bar { key: 2, value: 2}, Bar { key: 3, value: 3 }],
};
let value = &foo.value[1].value;
let obj = unsafe { hun::container_of!(value, Foo, value[1].value) };
assert_eq!(obj as *const _, &foo as *const _);