首页 > 解决方案 > 如何在 Rust 中安全地构造指向 LV2 原子 DST 的胖指针/指针?

问题描述

我正在为 Rust 集成 LV2 原子,它们是基于切片的动态大小类型 (DST)。一般来说,原子是由主机或其他插件创建的,我的代码只收到一个指向它们的细指针。因此,我需要从一个瘦指针创建一个指向基于切片的 DST 的胖指针。这就是我的代码大致如下所示:

#[repr(C)]
struct Atom {
    /// The len of the `data` field.
    len: u32,
    /// The data. 
    data: [u8],
}

/// This is the host. It creates the atom in a generally unknown way and calls
/// the plugin's run function. This isn't really part of my code, but it is
/// needed to understand it.
fn host() {
    // The raw representation of the atom
    let raw_representation: [u8; 8] = [
        // len: Raw representation of a `u32`. We have four data bytes.
        4, 0, 0, 0,
        // The actual data:
        1, 2, 3, 4
    ];

    let ptr: *const u8 = raw_representation.as_ptr();

    plugin_run(ptr);
}

/// This function represents the plugin's run function:
/// It only knows the pointer to the atom, nothing more.
fn plugin_run(ptr: *const u8) {
    // The length of the data.
    let len: u32 = *unsafe { (ptr as *const u32).as_ref() }.unwrap();

    // The "true" representation of the fat pointer.
    let fat_pointer: (*const u8, usize) = (ptr, len as usize);

    // transmuting the tuple into the actuall raw pointer.
    let atom: *const Atom = unsafe { std::mem::transmute(fat_pointer) };

    println!("{:?}", &atom.data);
}

有趣的行是倒数第二行plugin_run: 这里,一个胖指针是通过转换一个包含瘦指针和长度的元组来创建的。这种方法有效,但它使用了高度不安全的transmute方法。根据文档,这种方法应该是绝对的最后手段,但据我了解 Rust 的设计,我没有做任何不安全的事情。我只是在创建一个指针!

我不想坚持这个解决方案。除了使用之外,是否有一种安全的方法来创建指向基于数组的结构的指针transmute

唯一朝着这个方向发展的是std::slice::from_raw_parts,但它也是不安全的,直接创建引用,而不是指针,并且专门用于切片。我在标准库中一无所获,我在 crates.io 上一无所获,我什至在 git repo 中也没有发现任何问题。我在搜索错误的关键字吗?Rust 真的欢迎这样的事情吗?

如果不存在这样的东西,我会在 Rust 的 Github 存储库中为此创建一个问题。

编辑:我不应该对 LV2 说些什么,它使讨论朝着完全不同的方向发展。一切正常,我对数据模型进行了深入思考并对其进行了测试;我唯一想要的是一个安全的替代方法transmute来创建胖指针。:(

标签: pointerstypesreferencerustunsafe

解决方案


假设您想要动态大小的类型

将您的类型更改为允许默认为[u8]. 然后你可以取一个具体的值并得到未调整大小的版本:

#[repr(C)]
struct Atom<D: ?Sized = [u8]> {
    /// The len of the `data` field.
    len: u32,
    /// The data.
    data: D,
}

fn main() {
    let a1: &Atom = &Atom {
        len: 12,
        data: [1, 2, 3],
    };

    let a2: Box<Atom> = Box::new(Atom {
        len: 34,
        data: [4, 5, 6],
    });
}

也可以看看:

假设你想要 LV2 原子

我正在为 Rust 集成 LV2 原子

您是否有理由不使用处理此问题的现有板条箱

Rust 的 LV2 原子,它们是基于切片的动态大小类型

根据我能找到的源代码,它们不是。相反,它只使用结构组合:

typedef struct {
    uint32_t size;  /**< Size in bytes, not including type and size. */
    uint32_t type;  /**< Type of this atom (mapped URI). */
} LV2_Atom;

/** An atom:Int or atom:Bool.  May be cast to LV2_Atom. */
typedef struct {
    LV2_Atom atom;  /**< Atom header. */
    int32_t  body;  /**< Integer value. */
} LV2_Atom_Int;

官方文档似乎同意。这意味着永远LV2_Atom取值可能是无效的,因为您只会复制标题,而不是正文。这通常称为结构撕裂


在 Rust 中,这可以实现为:

use libc::{int32_t, uint32_t};

#[repr(C)]
struct Atom {
    size: uint32_t,
    r#type: uint32_t,
}

#[repr(C)]
struct Int {
    atom: Atom,
    body: int32_t,
}

const INT_TYPE: uint32_t = 42; // Not real

extern "C" {
    fn get_some_atom() -> *const Atom;
}

fn get_int() -> Option<*const Int> {
    unsafe {
        let a = get_some_atom();
        if (*a).r#type == INT_TYPE {
            Some(a as *const Int)
        } else {
            None
        }
    }
}

fn use_int() {
    if let Some(i) = get_int() {
        let val = unsafe { (*i).body };
        println!("{}", val);
    }
}

如果你查看lv2_raw crate的源代码,你会看到很多相同的东西。还有一个lv2 crate试图带来更高级别的界面。


推荐阅读