我正在写一个铁 rust 库,在那里我用了embedded-alloc.我希望我的库的用户能够根据他们的平台配置堆的大小,它是一个静态array.

我试过这样的方法,但不起作用:

#![no_std]
#![no_main]
extern crate alloc;

use cortex_m_rt::entry;
use embedded_alloc::LlffHeap as Heap;

#[global_allocator]
static HEAP: Heap = Heap::empty();

fn init<const N: usize>() {
     use core::mem::MaybeUninit;
     const HEAP_SIZE: usize = N;
     static mut HEAP_MEM: [MaybeUninit<u8>; HEAP_SIZE] = [MaybeUninit::uninit(); HEAP_SIZE];
     unsafe { HEAP.init(HEAP_MEM.as_ptr() as usize, HEAP_SIZE) }
}
// User code.
fn main() {
    init::<1024>();
}
error[E0401]: can't use generic parameters from outer item
 --> src/main.rs:2:31
  |
1 | fn init<const N: usize>() {
  |               - const parameter from outer item
2 |     const HEAP_SIZE: usize = N;
  |                               ^ use of generic parameter from outer item

For more information about this error, try `rustc --explain E0401`.
error: could not compile `rust_const_generic` (bin "rust_const_generic") due to previous error

有没有办法允许我的机箱的用户配置内部静态数组的大小?

推荐答案

你可以把它变成macro,而不是init()function.宏可以使用它们获得的参数声明static项.

在库中,使用一些非API公开(但公开给宏)的函数来初始化堆,给出一个指向静态:

#[doc(hidden)]
pub unsafe fn init_impl(start: *mut u8, size: usize) {
    HEAP.init(start as usize, size);
}

#[doc(hidden)]
pub use core::mem::MaybeUninit;

#[macro_export]
macro_rules! init {
    ( $size:expr $(,)? ) => {{
        const __MY_LIBRARY__HEAP_SIZE: usize = $size;
        static mut __MY_LIBRARY__HEAP_MEM: [$crate::MaybeUninit<u8>; __MY_LIBRARY__HEAP_SIZE] = [$crate::MaybeUninit::uninit(); __MY_LIBRARY__HEAP_SIZE];
        $crate::init_impl(__MY_LIBRARY__HEAP_MEM.as_mut_ptr().cast::<u8>(), __MY_LIBRARY__HEAP_SIZE);
    }};
}

然后在用户代码中:

fn main() {
    init!(1024);
}

Rust相关问答推荐

Rust中的相互递归特性与默认实现

文档示例需要导入相关的 struct ,但仅在运行测试时.这是故意的行为吗?

我如何在Rust中使用传递依赖中的特征?

为什么我不能从带有字符串的 struct 的引用迭代器中收集VEC<;&;str&>?

修改切片/引用数组

在Rust中,如果Result是Err,运行副作用(如日志(log)记录)的惯用方法是什么

无法实现整型类型的泛型FN

在Rust中声明和定义一个 struct 体有什么区别

获取已知数量的输入

Rust,如何从 Rc> 复制内部值并返回它?

根据掩码将 simd 通道设置为 0 的惯用方法?

如何使用 Bincode 在 Rust 中序列化 Enum,同时保留 Enum 判别式而不是索引?

面临意外的未对齐指针取消引用:地址必须是 0x8 的倍数,但为 0x__错误

为什么这个闭包没有实现Fn?

Sized问题的动态调度迭代器Rust

缺失serde的字段无法设置为默认值

内部值发生变化时 Rc 的行为

为什么1..=100返回一个范围而不是一个整数?

为什么这个闭包没有比 var 长寿?

将 reqwest bytes_stream 复制到 tokio 文件中