Proper storage of Rust Rc <T> in C-managed memory

I am wrapping a Rust object to be used from Lua. I need the object to be destroyed when neither Rust nor Lua code still refer to it, so the obvious (for me) solution is to use Rc<T>stored in Lua managed memory.

The Lua API (now I use rust-lua53 ) allows me to allocate a piece of memory, as well as attach methods and a finalizer to it, so I want to save Rc<T>this piece of memory.

My current attempt looks like. Firstly, creating an object:

/* Allocate a block of uninitialized memory to use */
let p = state.new_userdata(mem::size_of::<Rc<T>>() as size_t) as *mut Rc<T>;
/* Make a ref-counted pointer to a Rust object */
let rc = Rc::<T>::new(...);
/* Store the Rc */
unsafe { ptr::write(p, rc) };

And in the finalist:

let p: *mut Rc<T> = ...; /* Get a pointer to the item to finalize */
unsafe { ptr::drop_in_place(p) };  /* Release the object */

( println!() drop). ( , )? Rust, , ptr:: write Rc<T>.

, Rc<T> , Option<Rc<T>>; drop_in_place() ptr::swap() None. .

+4
2

( println!() drop). ( , )? Rust, , ptr:: write Rc<T>.

, ptr::write Rust . "" Rc<T>, - .

, Rust , , . , Arc.

, .


, Rc<T> , Option<Rc<T>>; drop_in_place() ptr:: swap() None. .

ptr::write ptr::read. , , ptr::read drop_in_place(), ptr::read ( ) , Rc<T>. , - , Rust.


new_userdata_typed new_userdata, . , postfix _typed .

+5

; , , drop_in_place(p) Rc T , , .

+1

All Articles