对齐结构成员,但不结构
我正在编写一些与C接口的生锈代码。C定义了一些结构,例如
struct foo {
// other fields
uint32_t count;
const struct bar* array;
};
我想通过此布局来定义锈结构,但是为了安全,我想放置count
和array < /code>在自己作为私人成员的结构中,就像这样:
#[repr(C)]
pub struct Foo {
// other fields
pub bars: BarSlice,
}
#[repr(C)]
pub struct BarSlice {
count: u32,
ptr: *const Bar,
}
这是错误的,因为在64位系统上,barslice将与8个字节保持一致,并且在count> Count
之前的字段可能是8个字节对齐和4个字节长。我如何告诉Rust正确对齐结构的成员,但不必担心结构本身?
我也宁愿避免在可能的情况下
- 为每个对齐情况创建不同的切片类型,
- 其中
foo
I'm writing some Rust code that interfaces with C. The C defines some structures like
struct foo {
// other fields
uint32_t count;
const struct bar* array;
};
I want to define a Rust structure with this layout, but for safety I want to put count
and array
in their own structure as private members, like so:
#[repr(C)]
pub struct Foo {
// other fields
pub bars: BarSlice,
}
#[repr(C)]
pub struct BarSlice {
count: u32,
ptr: *const Bar,
}
This is wrong though, since on 64-bit systems BarSlice will be aligned to 8 bytes, and the field immediately before count
might be 8 byte aligned and 4 bytes long. How can I tell Rust to align the members of the struct correctly, but not worry about the struct itself?
I would also rather avoid if possible
- creating a different slice type for each alignment circumstance
- having private fields in
Foo
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论