How to allocate structs on the heap without taking up space on the stack in stable Rust?

前端 未结 4 457
北荒
北荒 2020-12-19 07:45

In this code...

struct Test { a: i32, b: i64 }
    
fn foo() -> Box {              // Stack frame:
            


        
4条回答
  •  遥遥无期
    2020-12-19 08:34

    I recently had the same problem. Based on the answers here and other places, I wrote a simple function for heap allocation:

    pub fn unsafe_allocate() -> Box {
        let mut grid_box: Box;
        unsafe {
            use std::alloc::{alloc, dealloc, Layout};
            let layout = Layout::new::();
            let ptr = alloc(layout) as *mut T;
            grid_box = Box::from_raw(ptr);
        }
        return grid_box;
    }
    

    This will create a region in memory automatically sized after T and unsafely convince Rust that that memory region is an actual T value. The memory may contain arbitrary data; you should not assume all values are 0.

    Example use:

    let mut triangles: Box<[Triangle; 100000]> = unsafe_allocate::<[Triangle; 100000]>();
    

提交回复
热议问题