Skip to content

Commit

Permalink
Add some helper templates to cxx.h
Browse files Browse the repository at this point in the history
`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<MyTypeA>;

        #[namespace = "rust"]
        #[cxx_name = "make_unique"]
        fn make_MyTypeB(arg1: u32, arg2: bool) -> UniquePtr<MyTypeB>;

	#[namespace = "rust"]
        #[cxx_name = "shared_as_mutable]
        unsafe fn make_mutable_MyTypeA(ptr: &SharedPtr<MyTypeA>) -> Pin<&mut MyTypeA>;
    }
}
```
  • Loading branch information
jsgf committed Sep 18, 2021
1 parent 36d9ac1 commit a7b691b
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions include/cxx.h
Expand Up @@ -8,6 +8,7 @@
#include <initializer_list>
#include <iosfwd>
#include <iterator>
#include <memory>
#include <new>
#include <stdexcept>
#include <string>
Expand Down Expand Up @@ -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 <typename T, typename... Targs>
std::shared_ptr<T> make_shared(Targs... args) {
return std::make_shared<T>(args...);
}

// Unsafe function to give a Pin<&mut T> from a SharedPtr<T>.
template <typename T>
T& shared_as_mutable(std::shared_ptr<T> 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 <typename T, typename... Targs>
std::unique_ptr<T> make_unique(Targs... args) {
return std::make_unique<T>(args...);
}
#endif // c++14
#endif // CXXBRIDGE1_RUST_UNIQUE

template <typename T>
std::size_t size_of();
template <typename T>
Expand Down

0 comments on commit a7b691b

Please sign in to comment.