[Solved] How to hold Rust objects in Rust code created through C++?


To achieve that, we need a way to store the instances into a list of some kind, and return the index of the list to C++, so it works like a pointer to a Rust struct.

I can’t see why this would be the case. You don’t need a static list to return pointers from Rust. Simply allocate a Box in Rust and return it to the C++ code – a Box<T> with T: Sized has the same memory layout as a C pointer.

As explained in the linked documentation, your code can simply look like this:

// C++ header

// Returns ownership to the caller
extern "C" void *foo_new();

// Borrows mutably. The pointee cannot be changed by a different thread
// during the runtime of the function. The argument must be a pointer
// allocated with foo_new().
extern "C" void foo_transmogrify(void *);

// Takes ownership from the caller; no-op when invoked with NULL
extern "C" void foo_delete(void *);
#[repr(C)]
pub struct Foo {
    glonk: bool,
}

#[no_mangle]
pub extern "C" fn foo_new() -> Box<Foo> {
    Box::new(Foo { glonk: false })
}

#[no_mangle]
pub extern "C" fn foo_transmogrify(foo: &mut Foo) {
    foo.glonk = true;
}

#[no_mangle]
pub extern "C" fn foo_delete(_: Option<Box<Foo>>) {}

Note that the deallocation function can simply be empty. It will take ownership of the Box and implicitly drops it at the end of the function body.

9

solved How to hold Rust objects in Rust code created through C++?