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();

const HEAP_SIZE: usize = 65536;
static mut HEAP: [u8; HEAP_SIZE] = [0; HEAP_SIZE];

pub fn entry() {
    // SAFETY: `HEAP` is only used here and `entry` is only called once.
    unsafe {
        // Give the allocator some memory to allocate.
        HEAP_ALLOCATOR.lock().init(&raw mut HEAP as usize, HEAP_SIZE);
    }

    // Now we can do things that require heap allocation.
    let mut v = Vec::new();
    v.push("A string".to_string());
}
  • buddy_system_allocator is a crate implementing a basic buddy system allocator. Other crates are available, or you can write your own or hook into your existing allocator.
  • LockedHeap 的常量参数是分配器的最大阶数;即在本例中,它可以最多分配 2**32 字节大小的区域。
  • 如果依赖项树中的所有 crate 都依赖于 alloc,则您必须在二进制文件中明确定义一个全局分配器。通常,在顶级二进制 crate 中完成此操作。
  • 为了确保能够成功关联 panic_halt crate,以便我们获取其 panic 处理程序,必须使用 extern crate panic_halt as _ 方法。
  • 我们可以构建该示例,但由于没有入口点,无法运行。