Is there something like placement new?


#1

Say I allocate a piece of raw memory in C, and I want to initialize a struct on this piece of raw memory in rust, I will need such kind of things like placement new.

And there may be some other conditions when implementing a memory pool.


#2

You can use ptr::write or one of its variants to put Rust structs at a particular memory address.


#3

ptr::write makes sense if C has to do the allocation, but if you can avoid it, that’s probably even better; It’s always more complicated if memory allocation and memory usage happen on different sides of the FFI border.

It is quite common to have Rust allocate the Rust objects, and then using box::into_raw to get the raw pointer out to the C-side. (and box::from_raw to get it back into Rust)

I’m not sure how applicable this is, since you mention “memory pools”…


#4

Rust had experimental placement-new syntax, but removed it a few months ago. You can see a summary of that decision here: https://github.com/rust-lang/rust/issues/27779#issuecomment-378416911


#5

Note also you may need to use drop_in_place.
If not or reallocating unsafe { *ptr = val; } works.