Use a static Vec<u8> to handle shared memory

This commit is contained in:
Belén Albeza 2024-12-02 17:35:49 +01:00
parent df6727f186
commit 6623963a7f
3 changed files with 24 additions and 20 deletions

View file

@ -1,17 +1,25 @@
static mut BUFFERU8: Option<Box<Vec<u8>>> = None;
#[no_mangle]
pub extern "C" fn alloc_bytes(len: usize) -> *mut u8 {
// create a new mutable buffer with capacity `len`
let mut buf: Vec<u8> = Vec::with_capacity(len);
let ptr = buf.as_mut_ptr();
// take ownership of the memory block and ensure the its destructor is not
// called when the object goes out of scope at the end of the function
std::mem::forget(buf);
// TODO: Figure out how to deal with Result<T> from Emscripten
if unsafe { BUFFERU8.is_some() } {
panic!("Bytes already allocated");
}
let mut buffer = Box::new(Vec::<u8>::with_capacity(len));
let ptr = buffer.as_mut_ptr();
unsafe { BUFFERU8 = Some(buffer) };
return ptr;
}
pub fn free(ptr: *mut u8, len: usize) {
unsafe {
let buf = Vec::<u8>::from_raw_parts(ptr, len, len);
std::mem::forget(buf);
}
pub fn free_bytes() {
let buffer = unsafe { BUFFERU8.take() }.expect("uninitialized buffer");
std::mem::drop(buffer);
}
pub fn buffer_ptr() -> *mut u8 {
let buffer = unsafe { BUFFERU8.as_mut() }.expect("uninitializied buffer");
buffer.as_mut_ptr()
}