Skip to content

Conversation

@ekgame
Copy link
Collaborator

@ekgame ekgame commented Jan 17, 2026

This PR implemets a &malloc function to allocate memory that can then be passed to an FFI function as a pointer to populate it with data. The data can then be read back as bytes with &memcpy and freed with &memfree.

@ndren
Copy link
Contributor

ndren commented Jan 18, 2026

If the buffer is allocated with

let mut buffer = vec![0u8; size];

and deallocated with

unsafe { drop(Box::from_raw(ptr.get_mut())) };

is that valid? I'm not at all familiar with the exact semantics but I don't know if casting a Vec to a Box like that is promised to work and I can't find such a promise from the documentation. (I could be entirely wrong though, the code does work)

@kaikalii
Copy link
Member

If that's a concern, maybe allocate with Box::new_uninit_slice or Box::new_zeroed_slice instead. Then just get the pointer with Box::leak.

@ekgame
Copy link
Collaborator Author

ekgame commented Jan 18, 2026

If that's a concern, maybe allocate with Box::new_uninit_slice or Box::new_zeroed_slice instead. Then just get the pointer with Box::leak.

new_zeroed_slice is not stable yet (rust-lang/rust#129396), so I changed it to use new_uninit_slice.

@kaikalii kaikalii merged commit 1394621 into main Jan 18, 2026
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants