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,或是自行撰寫或連結至現有分配器。LockedHeap的 const 參數是分配器最高的階,意即在本例中,它最多可分配 2**32 個位元組的區域。- 如果依附元件樹狀結構中有任何 Crate 依附於
alloc,您就必須在二進位檔中只定義一個全域分配器。通常是在頂層二進位檔 Crate 中定義。 - 務必使用
extern crate panic_halt as _,確保panic_haltCrate 已連結,讓我們能取得其恐慌處理常式。 - 這個範例將建構但不執行,因為沒有進入點。