1. 指定堆分配器
以buddy_systme_allocator為例
use buddy_system_allocator::LockedHeap;
const HEAP_SIZE: usize = 1 << 20;
static mut HEAP_SPACE: [u8; HEAP_SIZE] = [0; HESP_SIZE];
#[global_allocator]
static GLOBAL_ALLOCATOR: LockedHeap = LockedHeap::empty();
fn init_heap() {
GLOBAL_ALLOCATOR
.lock()
.init(unsafe {HEAP_SPACE.as_ptr() as usize}, HEAP_SIZE);
}
fn main() {
init_heap();
let b = Box::new(2025usize);
}
2. 問題分析
問題一
unsafe {HEAP_SAPCE.as_ptr()}會報錯。
解決方案:
- 通過全局聲明
#![allow(static_mut_refs)]來解決 - 使用
addr_of_mut!宏
問題二
如果直接使用上述代碼在std模式下運(yùn)行,大概率是無法執(zhí)行的。原因是rust啟動的時候,會在執(zhí)行main函數(shù)之前進(jìn)行一些初始化工作(如堆棧的初始化)。而此時的GLOBAL_ALLOCATOR實(shí)際上尚未初始化(在執(zhí)行main函數(shù)的時候才完成初始化),導(dǎo)致在main函數(shù)之前需要進(jìn)行堆分配的工作失敗。
解決方案:
在main執(zhí)行前,完成堆的初始化??梢允褂?code>ctor屬性宏來實(shí)現(xiàn),該宏會將標(biāo)記的代碼鏈接到main函數(shù)執(zhí)行前。
// Cargo.toml
[dependencies]
ctor = "0.2.0"
use ctor::ctor;
#[ctor]
fn init_heap() {
GLOBAL_ALLOCATOR
.lock()
.init(unsafe {HEAP_SPACE.as_ptr() as usize}, HEAP_SIZE);
}
fn main() {
let b = Box::new(2025usize);
}