From a7b691b54ca18bcf244a35a2b587a39fe7ef019a Mon Sep 17 00:00:00 2001 From: Jeremy Fitzhardinge Date: Fri, 17 Sep 2021 16:15:09 -0700 Subject: [PATCH] Add some helper templates to cxx.h `rust::make_shared` - construct a type into a `std::shared_ptr` `rust::make_unique` - construct a type into a `std::unique_ptr` `rust::shared_as_mutable` - obtain a mutable reference to a `std::shared_ptr` value These are used as follows: ``` mod ffi { extern "C++" { type MyTypeA; type MyTypeB; #[namespace = "rust"] #[cxx_name = "make_shared"] fn make_MyTypeA(arg1: u32, arg2: bool) -> SharedPtr; #[namespace = "rust"] #[cxx_name = "make_unique"] fn make_MyTypeB(arg1: u32, arg2: bool) -> UniquePtr; #[namespace = "rust"] #[cxx_name = "shared_as_mutable] unsafe fn make_mutable_MyTypeA(ptr: &SharedPtr) -> Pin<&mut MyTypeA>; } } ``` --- include/cxx.h | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/include/cxx.h b/include/cxx.h index dffcb01ab..a816ca0a4 100644 --- a/include/cxx.h +++ b/include/cxx.h @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -414,6 +415,32 @@ class Opaque { }; #endif // CXXBRIDGE1_RUST_OPAQUE +#ifndef CXXBRIDGE1_RUST_SHARED +#define CXXBRIDGE1_RUST_SHARED +// Helper to construct a type into a std::shared_ptr. +template +std::shared_ptr make_shared(Targs... args) { + return std::make_shared(args...); +} + +// Unsafe function to give a Pin<&mut T> from a SharedPtr. +template +T& shared_as_mutable(std::shared_ptr const &ptr) { + return *ptr; +} +#endif // CXXBRIDGE1_RUST_SHARED + +#ifndef CXXBRIDGE1_RUST_UNIQUE +#define CXXBRIDGE1_RUST_UNIQUE +#if __cplusplus >= 201402L // c++14 +// Helper to construct a type into a std::unique_ptr. +template +std::unique_ptr make_unique(Targs... args) { + return std::make_unique(args...); +} +#endif // c++14 +#endif // CXXBRIDGE1_RUST_UNIQUE + template std::size_t size_of(); template