Rust 中精确的内存布局控制? [英] Precise memory layout control in Rust?

查看:52
本文介绍了Rust 中精确的内存布局控制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,Rust 编译器可以对结构的每个字段进行打包、重新排序和添加填充.如果需要,如何指定精确的内存布局?

As far as I know, the Rust compiler is allowed to pack, reorder, and add padding to each field of a struct. How can I specify the precise memory layout if I need it?

在 C# 中,我有 StructLayout 属性,而在 C/C++ 中,我可以使用各种编译器扩展.我可以通过检查期望值位置的字节偏移量来验证内存布局.

In C#, I have the StructLayout attribute, and in C/C++, I could use various compiler extensions. I could verify the memory layout by checking the byte offset of expected value locations.

我想使用自定义着色器编写 OpenGL 代码,这需要精确的内存布局.有没有办法在不牺牲性能的情况下做到这一点?

I'd like to write OpenGL code employing custom shaders, which needs precise memory layout. Is there a way to do this without sacrificing performance?

推荐答案

FFI 指南,您可以向结构添加属性以使用与 C 相同的布局:

As described in the FFI guide, you can add attributes to structs to use the same layout as C:

#[repr(C)]
struct Object {
    a: i32,
    // other members
}

并且您还可以打包结构:

and you also have the ability to pack the struct:

#[repr(C, packed)]
struct Object {
    a: i32,
    // other members
}

为了检测内存布局是否正常,您可以初始化一个结构体并通过将指针转换为整数来检查偏移量是否正常:

And for detecting that the memory layout is ok, you can initialize a struct and check that the offsets are ok by casting the pointers to integers:

#[repr(C, packed)]
struct Object {
    a: u8,
    b: u16,
    c: u32, // other members
}

fn main() {
    let obj = Object {
        a: 0xaa,
        b: 0xbbbb,
        c: 0xcccccccc,
    };
    let a_ptr: *const u8 = &obj.a;
    let b_ptr: *const u16 = &obj.b;
    let c_ptr: *const u32 = &obj.c;

    let base = a_ptr as usize;

    println!("a: {}", a_ptr as usize - base);
    println!("b: {}", b_ptr as usize - base);
    println!("c: {}", c_ptr as usize - base);
}

输出:

a: 0
b: 1
c: 3

这篇关于Rust 中精确的内存布局控制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆