PageSourceSearch

https://cxx.rs/

html cxx.rs collected 2026-10-02 03:55:20 UTC 15,510 bytes, 266 lines download raw bytes

1<!DOCTYPE HTML>
2<html lang="en" class="light sidebar-visible" dir="ltr">
3    <head>
4        <!-- Book generated using mdBook -->
5        <meta charset="UTF-8">
6        <title>Rust ❤️ C++</title>
7
8
9        <!-- Custom HTML head -->
vendor: 72 bytes, lines 9-10
9
10        <script async src="https://www.googletagmanager.com/gtag/js?id=
10G-DG41MK6DDN
vendor: 20 bytes, lines 10-11
10"></script>
11        
11<script>
12          
vendor: 157 bytes, lines 12-15
12window.dataLayer = window.dataLayer || [];
13          function gtag(){dataLayer.push(arguments);}
14          gtag('js', new Date());
15          gtag('config', '
15G-DG41MK6DDN
vendor: 99 bytes, lines 15-16
15', {anonymize_ip: true, cookie_domain: 'cxx.rs', cookie_flags: 'samesite=strict;secure'});
16        
16</script>
16
17
18        <meta name="description" content="CXX — safe interop between Rust and C++ by David Tolnay. This library provides a safe mechanism for calling C++ code from Rust and Rust code from C++.">
19        <meta name="viewport" content="width=device-width, initial-scale=1">
20        <meta name="theme-color" content="#ffffff">
21
22        <link rel="icon" href="favicon.svg">
23        <link rel="shortcut icon" href="favicon.png">
24        <link rel="stylesheet" href="css/variables.css">
25        <link rel="stylesheet" href="css/general.css">
26        <link rel="stylesheet" href="css/chrome.css">
27
28        <!-- Fonts -->
29        <link rel="stylesheet" href="FontAwesome/css/font-awesome.css">
30        <link rel="stylesheet" href="fonts/fonts.css">
31
32        <!-- Highlight.js Stylesheets -->
33        <link rel="stylesheet" id="highlight-css" href="highlight.css">
34        <link rel="stylesheet" id="tomorrow-night-css" href="tomorrow-night.css" disabled="true">
35        <link rel="stylesheet" id="ayu-highlight-css" href="ayu-highlight.css" disabled="true">
36
37        <!-- Custom theme stylesheets -->
38        <link rel="stylesheet" href="css/cxx.css">
39
40
41        <!-- Provide site root to javascript -->
42        
42<script>
43            var path_to_root = "";
44            var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "navy" : "light";
45        </script>
45
46        <!-- Start loading toc.js asap -->
47        
47<script src="toc.js"></script>
47
48    <meta property="og:image" content="https://cxx.rs/cxx.png"><meta property="og:site_name" content="CXX"><meta property="og:title" content="CXX — safe interop between Rust and C++"><meta name="twitter:image:src" content="https://cxx.rs/cxx.png"><meta name="twitter:site" content="@davidtolnay"><meta name="twitter:card" content="summary"><meta name="twitter:title" content="CXX — safe interop between Rust and C++"></head>
49    <body>
50    <div id="body-container">
51        <!-- Work around some values being stored in localStorage wrapped in quotes -->
52        
52<script>
53            try {
54                var theme = localStorage.getItem('mdbook-theme');
55                var sidebar = localStorage.getItem('mdbook-sidebar');
56
57                if (theme.startsWith('"') && theme.endsWith('"')) {
58                    localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
59                }
60
61                if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
62                    localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
63                }
64            } catch (e) { }
65        </script>
65
66
67        <!-- Set the theme before any content is loaded, prevents flash -->
68        
68<script>const html = document.documentElement;
69html.classList.add('js');</script>
69
70
71        <input type="checkbox" id="sidebar-toggle-anchor" class="hidden">
72
73        <!-- Hide / unhide sidebar before it is displayed -->
74        
74<script>
75            var sidebar = null;
76            var sidebar_toggle = document.getElementById("sidebar-toggle-anchor");
77            if (document.body.clientWidth >= 1080) {
78                try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
79                sidebar = sidebar || 'visible';
80            } else {
81                sidebar = 'hidden';
82            }
83            sidebar_toggle.checked = sidebar === 'visible';
84            html.classList.remove('sidebar-visible');
85            html.classList.add("sidebar-" + sidebar);
86        </script>
86
87
88        <nav id="sidebar" class="sidebar" aria-label="Table of contents">
89            <!-- populated by js -->
90            <mdbook-sidebar-scrollbox class="sidebar-scrollbox"></mdbook-sidebar-scrollbox>
91            <noscript>
92                <iframe class="sidebar-iframe-outer" src="toc.html"></iframe>
93            </noscript>
94            <div id="sidebar-resize-handle" class="sidebar-resize-handle">
95                <div class="sidebar-resize-indicator"></div>
96            </div>
97        </nav>
98
99        <div id="page-wrapper" class="page-wrapper">
100
101            <div class="page">
102                <div id="menu-bar-hover-placeholder"></div>
103                <div id="menu-bar" class="menu-bar sticky">
104                    <div class="left-buttons">
105                        <label id="sidebar-toggle" class="icon-button" for="sidebar-toggle-anchor" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
106                            <i class="fa fa-bars"></i>
107                        </label>
108                        <button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list" style="display:none">
109                            <i class="fa fa-paint-brush"></i>
110                        </button>
111                        <ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
112                            <li role="none"><button role="menuitem" class="theme" id="light">Light</button></li>
113                            <li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
114                            <li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
115                            <li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
116                            <li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
117                        </ul>
118                        <button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
119                            <i class="fa fa-search"></i>
120                        </button>
121                    </div>
122
123                    <h1 class="menu-title"></h1>
124
125                    <div class="right-buttons">
126                        <a href="https://github.com/dtolnay/cxx" title="Git repository" aria-label="Git repository">
127                            <i id="git-repository-button" class="fa fa-github"></i>
128                        </a>
129
130                    </div>
131                </div>
132
133                <div id="search-wrapper" class="hidden">
134                    <form id="searchbar-outer" class="searchbar-outer">
135                        <input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
136                    </form>
137                    <div id="searchresults-outer" class="searchresults-outer hidden">
138                        <div id="searchresults-header" class="searchresults-header"></div>
139                        <ul id="searchresults">
140                        </ul>
141                    </div>
142                </div>
143
144                <!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
145                
145<script>
146                    document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
147                    document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
148                    Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
149                        link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
150                    });
151                </script>
151
152
153                <div id="content" class="content">
154                    <main>
155                        <div class="badges">
156<a href="https://github.com/dtolnay/cxx"><img src="https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github" alt="github" height="28" class="badge"></a><a href="https://crates.io/crates/cxx"><img src="https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust" alt="crates-io" height="28" class="badge"></a><a href="https://docs.rs/cxx"><img src="https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs" alt="docs-rs" height="28" class="badge"></a>
157</div>
158<h1 id="cxx--safe-interop-between-rust-and-c"><a class="header" href="#cxx--safe-interop-between-rust-and-c">CXX — safe interop between Rust and C++</a></h1>
159<p>This library provides a safe mechanism for calling C++ code from Rust and Rust
160code from C++. It carves out a regime of commonality where Rust and C++ are
161semantically very similar and guides the programmer to express their language
162boundary effectively within this regime. CXX fills in the low level stuff so
163that you get a safe binding, preventing the pitfalls of doing a foreign function
164interface over unsafe C-style signatures.</p>
165<div style="height:190px;width=718px;padding:44px 0 44px">
166<object type="image/svg+xml" data="overview.svg"></object>
167</div>
168<p>From a high level description of the language boundary, CXX uses static analysis
169of the types and function signatures to protect both Rust's and C++'s
170invariants. Then it uses a pair of code generators to implement the boundary
171efficiently on both sides together with any necessary static assertions for
172later in the build process to verify correctness.</p>
173<p>The resulting FFI bridge operates at zero or negligible overhead, i.e. no
174copying, no serialization, no memory allocation, no runtime checks needed.</p>
175<p>The FFI signatures are able to use native data structures from whichever side
176they please. In addition, CXX provides builtin bindings for key standard library
177types like strings, vectors, Box, unique_ptr, etc to expose an idiomatic API on
178those types to the other language.</p>
179<h2 id="example"><a class="header" href="#example">Example</a></h2>
180<p>In this example we are writing a Rust application that calls a C++ client of a
181large-file blobstore service. The blobstore supports a <code class="hljs">put</code> operation for a
182discontiguous buffer upload. For example we might be uploading snapshots of a
183circular buffer which would tend to consist of 2 pieces, or fragments of a file
184spread across memory for some other reason (like a rope data structure).</p>
185<pre><code class="noplayground hidelines hide-boring hljs"><span class="hljs-meta">#[cxx::bridge]</span>
186<span class="hljs-keyword">mod</span> ffi {
187    <span class="hljs-keyword">extern</span> <span class="hljs-string">&quot;Rust&quot;</span> {
188        <span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">MultiBuf</span></span>;
189
190        <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">next_chunk</span></span>(buf: &amp;<span class="hljs-keyword">mut</span> MultiBuf) -&gt; &amp;[<span class="hljs-built_in">u8</span>];
191    }
192
193    <span class="hljs-keyword">unsafe</span> <span class="hljs-keyword">extern</span> <span class="hljs-string">&quot;C++&quot;</span> {
194        include!(<span class="hljs-string">&quot;example/include/blobstore.h&quot;</span>);
195
196        <span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">BlobstoreClient</span></span>;
197
198        <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">new_blobstore_client</span></span>() -&gt; UniquePtr&lt;BlobstoreClient&gt;;
199        <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">put</span></span>(<span class="hljs-keyword">self</span>: &amp;BlobstoreClient, buf: &amp;<span class="hljs-keyword">mut</span> MultiBuf) -&gt; <span class="hljs-built_in">Result</span>&lt;<span class="hljs-built_in">u64</span>&gt;;
200    }
201}</code></pre>
202<p>Now we simply provide Rust definitions of all the things in the <code class="hljs">extern "Rust"</code>
203block and C++ definitions of all the things in the <code class="hljs">extern "C++"</code> block, and get
204to call back and forth safely.</p>
205<p>The <a href="tutorial.html"><em><strong>Tutorial</strong></em></a> chapter walks through a fleshed out version of
206this blobstore example in full detail, including all of the Rust code and all of
207the C++ code. The code is also provided in runnable form in the <em>demo</em> directory
208of <a href="https://github.com/dtolnay/cxx">https://github.com/dtolnay/cxx</a>. To try it out, run <code class="hljs">cargo run</code> from that
209directory.</p>
210<ul>
211<li><a href="https://github.com/dtolnay/cxx/blob/master/demo/src/main.rs">demo/src/main.rs</a></li>
212<li><a href="https://github.com/dtolnay/cxx/blob/master/demo/include/blobstore.h">demo/include/blobstore.h</a></li>
213<li><a href="https://github.com/dtolnay/cxx/blob/master/demo/src/blobstore.cc">demo/src/blobstore.cc</a></li>
214</ul>
215<p>The key takeaway, which is enabled by the CXX library, is that the Rust code in
216main.rs is 100% ordinary safe Rust code working idiomatically with Rust types
217while the C++ code in blobstore.cc is 100% ordinary C++ code working
218idiomatically with C++ types. The Rust code feels like Rust and the C++ code
219feels like C++, not like C-style "FFI glue".</p>
220<br>
221<p><em><strong>Chapter outline:</strong> See the hamburger menu in the top left if you are on a
222small screen and it didn't open with a sidebar by default.</em></p>
223
224                    </main>
225
226                    <nav class="nav-wrapper" aria-label="Page navigation">
227                        <!-- Mobile navigation buttons -->
228
229                            <a rel="next prefetch" href="concepts.html" class="mobile-nav-chapter
229s next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
230                                <i class="fa fa-angle-right"></i>
231                            </a>
232
233                        <div style="clear: both"></div>
234                    </nav>
235                </div>
236            </div>
237
238            <nav class="nav-wide-wrapper" aria-label="Page navigation">
239
240                    <a rel="next prefetch" href="concepts.html" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
241                        <i class="fa fa-angle-right"></i>
242                    </a>
243            </nav>
244
245        </div>
246
247
248
249
250
251
252        
252<script src="elasticlunr.min.js"></script>
252
253        
253<script src="mark.min.js"></script>
253
254        
254<script src="searcher.js"></script>
254
255
256        
256<script src="clipboard.min.js"></script>
256
257        
257<script src="highlight.js"></script>
257
258        
258<script src="book.js"></script>
258
259
260        <!-- Custom JS scripts -->
261
262
263    </div>
264    
264<script type="module" src="https://static.cloudflareinsights.com/beacon.min.js/v31edd6df95cf4e85bb4c19e7a9bdbcba1788362987495" integrity="sha512-iIg7k2xntmwu6/uSb5tpc/hySgZc4eoL31yB29W6tJFo2akwjPWcEqnCEdJvGexCL0KEQwVYv5BlowfhVz26hg==" data-cf-beacon='{"version":"2024.11.0","token":"52f3d06a9d20405a95b25c56202ed5e8","r":1,"spa":2}' crossorigin="anonymous"></script>
264
265</body>
266</html>

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.