2个版本
0.1.1 | 2023年12月25日 |
---|---|
0.1.0 | 2023年8月22日 |
#7 in #c-like
每月 39 次下载
在 hirun 中使用
7KB
95 行
hioff
原始名称是 hun_offsetof
。提供类似C的宏:offset_of
和 container_of
接口
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 _);
lib.rs
:
提供类似C的宏:offset_of和container_of
示例
extern crate hioff 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 _);
依赖
~1.5MB
~35K SLoC