Implement returning unique_ptr from Rust to C++

This commit is contained in:
David Tolnay 2020-03-06 16:14:00 -08:00
parent 5cd8d61f9d
commit 4b3a66edf1
No known key found for this signature in database
GPG Key ID: F9BA143B95FF6D82
3 changed files with 18 additions and 2 deletions

View File

@ -341,6 +341,10 @@ fn write_rust_function_shim(out: &mut OutFile, efn: &ExternFn, types: &Types) {
write_type(out, ret);
write!(out, "::from_raw(");
}
Type::UniquePtr(_) => {
write_type(out, ret);
write!(out, "(");
}
Type::Ref(_) => write!(out, "*"),
_ => {}
}
@ -375,7 +379,7 @@ fn write_rust_function_shim(out: &mut OutFile, efn: &ExternFn, types: &Types) {
}
write!(out, ")");
if let Some(ret) = &efn.ret {
if let Type::RustBox(_) = ret {
if let Type::RustBox(_) | Type::UniquePtr(_) = ret {
write!(out, ")");
}
}

View File

@ -37,7 +37,7 @@ pub mod ffi {
fn r_return_primitive() -> usize;
fn r_return_shared() -> Shared;
fn r_return_box() -> Box<R>;
//TODO fn r_return_unique_ptr() -> UniquePtr<C>;
fn r_return_unique_ptr() -> UniquePtr<C>;
fn r_return_ref(shared: &Shared) -> &usize;
fn r_return_str(shared: &Shared) -> &str;
fn r_return_rust_string() -> String;
@ -69,6 +69,13 @@ fn r_return_box() -> Box<R> {
Box::new(2020)
}
fn r_return_unique_ptr() -> UniquePtr<ffi::C> {
extern "C" {
fn cxx_test_suite_get_unique_ptr() -> *mut ffi::C;
}
unsafe { UniquePtr::from_raw(cxx_test_suite_get_unique_ptr()) }
}
fn r_return_ref(shared: &ffi::Shared) -> &usize {
&shared.z
}

View File

@ -90,6 +90,10 @@ void c_take_unique_ptr_string(std::unique_ptr<std::string> s) {
}
}
extern "C" C *cxx_test_suite_get_unique_ptr() {
return std::unique_ptr<C>(new C{2020}).release();
}
extern "C" const char *cxx_run_test() noexcept {
#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)
@ -103,6 +107,7 @@ extern "C" const char *cxx_run_test() noexcept {
ASSERT(r_return_primitive() == 2020);
ASSERT(r_return_shared().z == 2020);
ASSERT(cxx_test_suite_r_is_correct(&*r_return_box()));
ASSERT(r_return_unique_ptr()->get() == 2020);
ASSERT(r_return_ref(Shared{2020}) == 2020);
ASSERT(std::string(r_return_str(Shared{2020})) == "2020");
ASSERT(std::string(r_return_rust_string()) == "2020");