对齐结构成员,但不结构

发布于 2025-01-23 11:08:55 字数 675 浏览 3 评论 0原文

我正在编写一些与C接口的生锈代码。C定义了一些结构,例如

struct foo {
    // other fields
    uint32_t count;
    const struct bar* array;
};

我想通过此布局来定义锈结构,但是为了安全,我想放置countarray < /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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文