• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1{{#title Attributes — Rust ♡ C++}}
2# Attributes
3
4## namespace
5
6The top-level cxx::bridge attribute macro takes an optional `namespace` argument
7to control the C++ namespace into which to emit extern Rust items and the
8namespace in which to expect to find the extern C++ items.
9
10```rust,noplayground
11#[cxx::bridge(namespace = "path::of::my::company")]
12mod ffi {
13    extern "Rust" {
14        type MyType;  // emitted to path::of::my::company::MyType
15    }
16
17    extern "C++" {
18        type TheirType;  // refers to path::of::my::company::TheirType
19    }
20}
21```
22
23Additionally, a `#[namespace = "..."]` attribute may be used inside the bridge
24module on any extern block or individual item. An item will inherit the
25namespace specified on its surrounding extern block if any, otherwise the
26namespace specified with the top level cxx::bridge attribute if any, otherwise
27the global namespace.
28
29```rust,noplayground
30#[cxx::bridge(namespace = "third_priority")]
31mod ffi {
32    #[namespace = "second_priority"]
33    extern "Rust" {
34        fn f();
35
36        #[namespace = "first_priority"]
37        fn g();
38    }
39
40    extern "Rust" {
41        fn h();
42    }
43}
44```
45
46The above would result in functions `::second_priority::f`,
47`::first_priority::g`, `::third_priority::h`.
48
49## rust\_name, cxx\_name
50
51Sometimes you want the Rust name of a function or type to differ from its C++
52name. Importantly, this enables binding multiple overloads of the same C++
53function name using distinct Rust names.
54
55```rust,noplayground
56#[cxx::bridge]
57mod ffi {
58    unsafe extern "C++" {
59        #[rust_name = "i32_overloaded_function"]
60        fn cOverloadedFunction(x: i32) -> String;
61        #[rust_name = "str_overloaded_function"]
62        fn cOverloadedFunction(x: &str) -> String;
63    }
64}
65```
66
67The `#[rust_name = "..."]` attribute replaces the name that Rust should use for
68this function, and an analogous `#[cxx_name = "..."]` attribute replaces the
69name that C++ should use.
70
71Either of the two attributes may be used on extern "Rust" as well as extern
72"C++" functions, according to which one you find clearer in context.
73
74The same attribute works for renaming functions, opaque types, shared
75structs and enums, and enum variants.
76