alloc

如需使用 alloc,您必须实现 全局(堆)分配器

#![no_main]
#![no_std]

extern crate alloc;
extern crate panic_halt as _;

use alloc::string::ToString;
use alloc::vec::Vec;
use buddy_system_allocator::LockedHeap;

#[global_allocator]
static HEAP_ALLOCATOR: LockedHeap<32> = LockedHeap::<32>::new();

static mut HEAP: [u8; 65536] = [0; 65536];

pub fn entry() {
    // Safe because `HEAP` is only used here and `entry` is only called once.
    unsafe {
        // Give the allocator some memory to allocate.
        HEAP_ALLOCATOR.lock().init(HEAP.as_mut_ptr() as usize, HEAP.len());
    }

    // Now we can do things that require heap allocation.
    let mut v = Vec::new();
    v.push("A string".to_string());
}
  • buddy_system_allocator 是第三方 crate,用于实现基本伙伴系统分配器。还可以使用其他 crate,或者自行编写 crate,或者接入现有分配器。
  • LockedHeap 的常量参数是分配器的最大阶数;即在本例中,它可以最多分配 2**32 字节大小的区域。
  • 如果依赖项树中的所有 crate 都依赖于 alloc,则您必须在二进制文件中明确定义一个全局分配器。通常,在顶级二进制 crate 中完成此操作。
  • 为了确保能够成功关联 panic_halt crate,以便我们获取其 panic 处理程序,必须使用 extern crate panic_halt as _ 方法。
  • 我们可以构建该示例,但由于没有入口点,无法运行。