File tree Expand file tree Collapse file tree 2 files changed +90
-0
lines changed
Expand file tree Collapse file tree 2 files changed +90
-0
lines changed Original file line number Diff line number Diff line change 3232 - [ SharedPtr\< T\> &mdash ; std::shared\_ ptr\< T\> ] ( binding/sharedptr.md )
3333 - [ Vec\< T\> &mdash ; rust::Vec\< T\> ] ( binding/vec.md )
3434 - [ CxxVector\< T\> &mdash ; std::vector\< T\> ] ( binding/cxxvector.md )
35+ - [ Option\< T\> &mdash ; rust::Option\< T\> ] ( binding/option.md )
3536 - [ * mut T, * const T raw pointers] ( binding/rawptr.md )
3637 - [ Function pointers] ( binding/fn.md )
3738 - [ Result\< T\> ] ( binding/result.md )
Original file line number Diff line number Diff line change 1+ {{#title rust::Option<T > — Rust ♡ C++}}
2+ # rust::Option\< T\>
3+
4+ ### Public API:
5+
6+ ``` cpp,hidelines=...
7+ // rust/cxx.h
8+ ...
9+ ...namespace rust {
10+
11+ template <typename T>
12+ class Option final {
13+ public:
14+ Option() noexcept;
15+ Option(Option&&) noexcept;
16+ Option(T&&) noexcept;
17+ ~Option() noexcept;
18+
19+ const T *operator->() const;
20+ const T &operator*() const;
21+ T *operator->();
22+ T &operator*();
23+
24+ Option<T>& operator=(Option&&) noexcept;
25+
26+ bool has_value() const noexcept;
27+ T& value() noexcept;
28+ void reset();
29+ void set(T&&) noexcept;
30+ };
31+ ...} // namespace rust
32+ ```
33+
34+ ### Restrictions:
35+
36+ Option<T > only supports pointer-sized references and Box-es; that is, no
37+ fat pointers like &str (though &String is supported) or Box<[ u8] >. On the
38+ C++ side, Option<&T> becomes rust::Option<const T* > (and similar for
39+ mutable references), but the pointer is guaranteed to be non-null if the
40+ Option has a value. Also, you can only pass Options themselves by value.
41+ &Option<T > is not allowed.
42+
43+ ## Example
44+
45+ ``` rust,noplayground
46+ // src/main.rs
47+
48+ #[cxx::bridge]
49+ mod ffi {
50+ struct Shared {
51+ v: u32,
52+ }
53+
54+ unsafe extern "C++" {
55+ include!("example/include/example.h");
56+
57+ fn f(elements: Option<&Shared>);
58+ }
59+ }
60+
61+ fn main() {
62+ let shared = Shared { v: 3 };
63+ ffi::f(Some(&shared));
64+ ffi::f(None);
65+ }
66+ ```
67+
68+ ``` cpp
69+ // include/example.h
70+
71+ #pragma once
72+ #include " example/src/main.rs.h"
73+ #include " rust/cxx.h"
74+
75+ void f (rust::Option<const Shared* >);
76+ ```
77+
78+ ```cpp
79+ // src/example.cc
80+
81+ #include "example/include/example.h"
82+
83+ void f(rust::Option<const Shared*> o) {
84+ if (o.has_value()) {
85+ // Pointer is guaranteed to be non-null
86+ std::cout << shared.value()->v << std::endl;
87+ }
88+ }
89+ ```
You can’t perform that action at this time.
0 commit comments