cxx
cxx copied to clipboard
Unable to use SharedPtr<T> to shared type
I have some C++ code that needs to be able to construct and interact Rust objects that I can't add to the shared Rust interface. My solution has been to create a shim struct that is shared that holds a Boxed instance of the opaque Rust object. So I've defined shared structure and function like so:
#[cxx::bridge(namespace = "test")]
mod ffi {
extern "Rust" {
type RustFoo;
struct CppFoo {
inner: Box<RustFoo>,
}
fn new_Foo() -> UniquePtr<CppFoo>;
fn do_something(self: &CppFoo);
}
}
impl ffi::CppFoo {
pub fn do_something(&self) {
self.inner.something();
}
}
fn new_Foo() -> UniquePtr<ffi::CppFoo> {
let t = ffi::CppFoo { inner: Box::new(RustFoo::new()) };
return UniquePtr::new(t);
}
This all works with UniquePtr but with SharedPtr I get the error:
fn new_Foo() -> SharedPtr<ffi::CppFoo> {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `SharedPtrTarget` is not implemented for `CppFoo`
What am I doing missing or doing wrong? Or am I going about this the wrong way?
You need to add impl SharedPtr<CppFoo> {} inside the ffi module that defines CppFoo in order for SharedPtr<CppFoo> to work, if SharedPtr<CppFoo> isn't otherwise already mentioned in that module.
See https://cxx.rs/extern-c++.html#explicit-shim-trait-impls.
Thank you helped but now I'm getting a linker error when I try to link the generated .a library with the .so I'm creating.
The error looks something like this, I think it's saying that the rust .a library needs to be recompiled with -fPIC but I'm not sure how to do that with Rust.
relocation R_X86_64_PC32 against symbol `_ZTVSt15_Sp_counted_ptrIPN9test14CppFooELN9__gnu_cxx12_Lock_policyE2EE' can not be used when making a shared object; recompile with -fPIC