Copying Rc to foreign/C memory
ā Rust š 2025-11-29 š¤ surdeus šļø 4I think I see how to do this, but I want to double check here. Maybe there is a better idea.
I want to copy an Rc<Foo> or maybe an Rc<dyn Something> to an area of memory managed by another language. I think I can copy it into the memory like:
use std::ptr;
let rc: Rc<Foo> = ...
let mem: *mut Rc<Foo> = some_bytes as _;
ptr::write(mem, rc);
This will move it into the foreign memory, so the ref count will not go down, and the Rust memory will not be deallocated, even though (possibly) no Rc<Foo>s exist in Rust.
To get the value back out of C-land, Iām thinking I can use ptr::read:
let rc2: Rc<Foo> = ptr::read(mem);
But if I understand correctly, that will do a bitwise copy and nothing else, so I then need to use something like this: increment_strong_count, to account for this new rc2 value in Rust. Correct?
7 posts - 3 participants
š·ļø Rust_feed