Copying Rc to foreign/C memory

āš“ Rust    šŸ“… 2025-11-29    šŸ‘¤ surdeus    šŸ‘ļø 4      

surdeus

I 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

Read full topic

šŸ·ļø Rust_feed