| <!DOCTYPE HTML> |
| <html lang="en" class="light sidebar-visible" dir="ltr"> |
| <head> |
| <!-- Book generated using mdBook --> |
| <meta charset="UTF-8"> |
| <title>A little C with your Rust - The Embedded Rust Book</title> |
| |
| |
| <!-- Custom HTML head --> |
| |
| <meta name="description" content=""> |
| <meta name="viewport" content="width=device-width, initial-scale=1"> |
| <meta name="theme-color" content="#ffffff"> |
| |
| <link rel="icon" href="../favicon.svg"> |
| <link rel="shortcut icon" href="../favicon.png"> |
| <link rel="stylesheet" href="../css/variables.css"> |
| <link rel="stylesheet" href="../css/general.css"> |
| <link rel="stylesheet" href="../css/chrome.css"> |
| <link rel="stylesheet" href="../css/print.css" media="print"> |
| |
| <!-- Fonts --> |
| <link rel="stylesheet" href="../FontAwesome/css/font-awesome.css"> |
| <link rel="stylesheet" href="../fonts/fonts.css"> |
| |
| <!-- Highlight.js Stylesheets --> |
| <link rel="stylesheet" id="highlight-css" href="../highlight.css"> |
| <link rel="stylesheet" id="tomorrow-night-css" href="../tomorrow-night.css"> |
| <link rel="stylesheet" id="ayu-highlight-css" href="../ayu-highlight.css"> |
| |
| <!-- Custom theme stylesheets --> |
| |
| |
| <!-- Provide site root and default themes to javascript --> |
| <script> |
| const path_to_root = "../"; |
| const default_light_theme = "light"; |
| const default_dark_theme = "navy"; |
| </script> |
| <!-- Start loading toc.js asap --> |
| <script src="../toc.js"></script> |
| </head> |
| <body> |
| <div id="mdbook-help-container"> |
| <div id="mdbook-help-popup"> |
| <h2 class="mdbook-help-title">Keyboard shortcuts</h2> |
| <div> |
| <p>Press <kbd>←</kbd> or <kbd>→</kbd> to navigate between chapters</p> |
| <p>Press <kbd>S</kbd> or <kbd>/</kbd> to search in the book</p> |
| <p>Press <kbd>?</kbd> to show this help</p> |
| <p>Press <kbd>Esc</kbd> to hide this help</p> |
| </div> |
| </div> |
| </div> |
| <div id="body-container"> |
| <!-- Work around some values being stored in localStorage wrapped in quotes --> |
| <script> |
| try { |
| let theme = localStorage.getItem('mdbook-theme'); |
| let sidebar = localStorage.getItem('mdbook-sidebar'); |
| |
| if (theme.startsWith('"') && theme.endsWith('"')) { |
| localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1)); |
| } |
| |
| if (sidebar.startsWith('"') && sidebar.endsWith('"')) { |
| localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1)); |
| } |
| } catch (e) { } |
| </script> |
| |
| <!-- Set the theme before any content is loaded, prevents flash --> |
| <script> |
| const default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? default_dark_theme : default_light_theme; |
| let theme; |
| try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { } |
| if (theme === null || theme === undefined) { theme = default_theme; } |
| const html = document.documentElement; |
| html.classList.remove('light') |
| html.classList.add(theme); |
| html.classList.add("js"); |
| </script> |
| |
| <input type="checkbox" id="sidebar-toggle-anchor" class="hidden"> |
| |
| <!-- Hide / unhide sidebar before it is displayed --> |
| <script> |
| let sidebar = null; |
| const sidebar_toggle = document.getElementById("sidebar-toggle-anchor"); |
| if (document.body.clientWidth >= 1080) { |
| try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { } |
| sidebar = sidebar || 'visible'; |
| } else { |
| sidebar = 'hidden'; |
| } |
| sidebar_toggle.checked = sidebar === 'visible'; |
| html.classList.remove('sidebar-visible'); |
| html.classList.add("sidebar-" + sidebar); |
| </script> |
| |
| <nav id="sidebar" class="sidebar" aria-label="Table of contents"> |
| <!-- populated by js --> |
| <mdbook-sidebar-scrollbox class="sidebar-scrollbox"></mdbook-sidebar-scrollbox> |
| <noscript> |
| <iframe class="sidebar-iframe-outer" src="../toc.html"></iframe> |
| </noscript> |
| <div id="sidebar-resize-handle" class="sidebar-resize-handle"> |
| <div class="sidebar-resize-indicator"></div> |
| </div> |
| </nav> |
| |
| <div id="page-wrapper" class="page-wrapper"> |
| |
| <div class="page"> |
| <div id="menu-bar-hover-placeholder"></div> |
| <div id="menu-bar" class="menu-bar sticky"> |
| <div class="left-buttons"> |
| <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"> |
| <i class="fa fa-bars"></i> |
| </label> |
| <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"> |
| <i class="fa fa-paint-brush"></i> |
| </button> |
| <ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu"> |
| <li role="none"><button role="menuitem" class="theme" id="default_theme">Auto</button></li> |
| <li role="none"><button role="menuitem" class="theme" id="light">Light</button></li> |
| <li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li> |
| <li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li> |
| <li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li> |
| <li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li> |
| </ul> |
| <button id="search-toggle" class="icon-button" type="button" title="Search (`/`)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="/ s" aria-controls="searchbar"> |
| <i class="fa fa-search"></i> |
| </button> |
| </div> |
| |
| <h1 class="menu-title">The Embedded Rust Book</h1> |
| |
| <div class="right-buttons"> |
| <a href="../print.html" title="Print this book" aria-label="Print this book"> |
| <i id="print-button" class="fa fa-print"></i> |
| </a> |
| <a href="https://github.com/rust-embedded/book" title="Git repository" aria-label="Git repository"> |
| <i id="git-repository-button" class="fa fa-github"></i> |
| </a> |
| |
| </div> |
| </div> |
| |
| <div id="search-wrapper" class="hidden"> |
| <form id="searchbar-outer" class="searchbar-outer"> |
| <input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header"> |
| </form> |
| <div id="searchresults-outer" class="searchresults-outer hidden"> |
| <div id="searchresults-header" class="searchresults-header"></div> |
| <ul id="searchresults"> |
| </ul> |
| </div> |
| </div> |
| |
| <!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM --> |
| <script> |
| document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible'); |
| document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible'); |
| Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) { |
| link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1); |
| }); |
| </script> |
| |
| <div id="content" class="content"> |
| <main> |
| <h1 id="a-little-c-with-your-rust"><a class="header" href="#a-little-c-with-your-rust">A little C with your Rust</a></h1> |
| <p>Using C or C++ inside of a Rust project consists of two major parts:</p> |
| <ul> |
| <li>Wrapping the exposed C API for use with Rust</li> |
| <li>Building your C or C++ code to be integrated with the Rust code</li> |
| </ul> |
| <p>As C++ does not have a stable ABI for the Rust compiler to target, it is recommended to use the <code>C</code> ABI when combining Rust with C or C++.</p> |
| <h2 id="defining-the-interface"><a class="header" href="#defining-the-interface">Defining the interface</a></h2> |
| <p>Before consuming C or C++ code from Rust, it is necessary to define (in Rust) what data types and function signatures exist in the linked code. In C or C++, you would include a header (<code>.h</code> or <code>.hpp</code>) file which defines this data. In Rust, it is necessary to either manually translate these definitions to Rust, or use a tool to generate these definitions.</p> |
| <p>First, we will cover manually translating these definitions from C/C++ to Rust.</p> |
| <h3 id="wrapping-c-functions-and-datatypes"><a class="header" href="#wrapping-c-functions-and-datatypes">Wrapping C functions and Datatypes</a></h3> |
| <p>Typically, libraries written in C or C++ will provide a header file defining all types and functions used in public interfaces. An example file may look like this:</p> |
| <pre><code class="language-C">/* File: cool.h */ |
| typedef struct CoolStruct { |
| int x; |
| int y; |
| } CoolStruct; |
| |
| void cool_function(int i, char c, CoolStruct* cs); |
| </code></pre> |
| <p>When translated to Rust, this interface would look as such:</p> |
| <pre><code class="language-rust ignore">/* File: cool_bindings.rs */ |
| #[repr(C)] |
| pub struct CoolStruct { |
| pub x: cty::c_int, |
| pub y: cty::c_int, |
| } |
| |
| extern "C" { |
| pub fn cool_function( |
| i: cty::c_int, |
| c: cty::c_char, |
| cs: *mut CoolStruct |
| ); |
| }</code></pre> |
| <p>Let's take a look at this definition one piece at a time, to explain each of the parts.</p> |
| <pre><code class="language-rust ignore">#[repr(C)] |
| pub struct CoolStruct { ... }</code></pre> |
| <p>By default, Rust does not guarantee order, padding, or the size of data included in a <code>struct</code>. In order to guarantee compatibility with C code, we include the <code>#[repr(C)]</code> attribute, which instructs the Rust compiler to always use the same rules C does for organizing data within a struct.</p> |
| <pre><code class="language-rust ignore">pub x: cty::c_int, |
| pub y: cty::c_int,</code></pre> |
| <p>Due to the flexibility of how C or C++ defines an <code>int</code> or <code>char</code>, it is recommended to use primitive data types defined in <code>cty</code>, which will map types from C to types in Rust.</p> |
| <pre><code class="language-rust ignore">extern "C" { pub fn cool_function( ... ); }</code></pre> |
| <p>This statement defines the signature of a function that uses the C ABI, called <code>cool_function</code>. By defining the signature without defining the body of the function, the definition of this function will need to be provided elsewhere, or linked into the final library or binary from a static library.</p> |
| <pre><code class="language-rust ignore"> i: cty::c_int, |
| c: cty::c_char, |
| cs: *mut CoolStruct</code></pre> |
| <p>Similar to our datatype above, we define the datatypes of the function arguments using C-compatible definitions. We also retain the same argument names, for clarity.</p> |
| <p>We have one new type here, <code>*mut CoolStruct</code>. As C does not have a concept of Rust's references, which would look like this: <code>&mut CoolStruct</code>, we instead have a raw pointer. As dereferencing this pointer is <code>unsafe</code>, and the pointer may in fact be a <code>null</code> pointer, care must be taken to ensure the guarantees typical of Rust when interacting with C or C++ code.</p> |
| <h3 id="automatically-generating-the-interface"><a class="header" href="#automatically-generating-the-interface">Automatically generating the interface</a></h3> |
| <p>Rather than manually generating these interfaces, which may be tedious and error prone, there is a tool called <a href="https://github.com/rust-lang/rust-bindgen">bindgen</a> which will perform these conversions automatically. For instructions of the usage of <a href="https://github.com/rust-lang/rust-bindgen">bindgen</a>, please refer to the <a href="https://rust-lang.github.io/rust-bindgen/">bindgen user's manual</a>, however the typical process consists of the following:</p> |
| <ol> |
| <li>Gather all C or C++ headers defining interfaces or datatypes you would like to use with Rust.</li> |
| <li>Write a <code>bindings.h</code> file, which <code>#include "..."</code>'s each of the files you gathered in step one.</li> |
| <li>Feed this <code>bindings.h</code> file, along with any compilation flags used to compile |
| your code into <code>bindgen</code>. Tip: use <code>Builder.ctypes_prefix("cty")</code> / |
| <code>--ctypes-prefix=cty</code> and <code>Builder.use_core()</code> / <code>--use-core</code> to make the generated code <code>#![no_std]</code> compatible.</li> |
| <li><code>bindgen</code> will produce the generated Rust code to the output of the terminal window. This output may be piped to a file in your project, such as <code>bindings.rs</code>. You may use this file in your Rust project to interact with C/C++ code compiled and linked as an external library. Tip: don't forget to use the <a href="https://crates.io/crates/cty"><code>cty</code></a> crate if your types in the generated bindings are prefixed with <code>cty</code>.</li> |
| </ol> |
| <h2 id="building-your-cc-code"><a class="header" href="#building-your-cc-code">Building your C/C++ code</a></h2> |
| <p>As the Rust compiler does not directly know how to compile C or C++ code (or code from any other language, which presents a C interface), it is necessary to compile your non-Rust code ahead of time.</p> |
| <p>For embedded projects, this most commonly means compiling the C/C++ code to a static archive (such as <code>cool-library.a</code>), which can then be combined with your Rust code at the final linking step.</p> |
| <p>If the library you would like to use is already distributed as a static archive, it is not necessary to rebuild your code. Just convert the provided interface header file as described above, and include the static archive at compile/link time.</p> |
| <p>If your code exists as a source project, it will be necessary to compile your C/C++ code to a static library, either by triggering your existing build system (such as <code>make</code>, <code>CMake</code>, etc.), or by porting the necessary compilation steps to use a tool called the <code>cc</code> crate. For both of these steps, it is necessary to use a <code>build.rs</code> script.</p> |
| <h3 id="rust-buildrs-build-scripts"><a class="header" href="#rust-buildrs-build-scripts">Rust <code>build.rs</code> build scripts</a></h3> |
| <p>A <code>build.rs</code> script is a file written in Rust syntax, that is executed on your compilation machine, AFTER dependencies of your project have been built, but BEFORE your project is built.</p> |
| <p>The full reference may be found <a href="https://doc.rust-lang.org/cargo/reference/build-scripts.html">here</a>. <code>build.rs</code> scripts are useful for generating code (such as via <a href="https://github.com/rust-lang/rust-bindgen">bindgen</a>), calling out to external build systems such as <code>Make</code>, or directly compiling C/C++ through use of the <code>cc</code> crate.</p> |
| <h3 id="triggering-external-build-systems"><a class="header" href="#triggering-external-build-systems">Triggering external build systems</a></h3> |
| <p>For projects with complex external projects or build systems, it may be easiest to use <a href="https://doc.rust-lang.org/std/process/struct.Command.html"><code>std::process::Command</code></a> to "shell out" to your other build systems by traversing relative paths, calling a fixed command (such as <code>make library</code>), and then copying the resulting static library to the proper location in the <code>target</code> build directory.</p> |
| <p>While your crate may be targeting a <code>no_std</code> embedded platform, your <code>build.rs</code> executes only on machines compiling your crate. This means you may use any Rust crates which will run on your compilation host.</p> |
| <h3 id="building-cc-code-with-the-cc-crate"><a class="header" href="#building-cc-code-with-the-cc-crate">Building C/C++ code with the <code>cc</code> crate</a></h3> |
| <p>For projects with limited dependencies or complexity, or for projects where it is difficult to modify the build system to produce a static library (rather than a final binary or executable), it may be easier to instead utilize the <a href="https://github.com/alexcrichton/cc-rs"><code>cc</code> crate</a>, which provides an idiomatic Rust interface to the compiler provided by the host.</p> |
| <p>In the simplest case of compiling a single C file as a dependency to a static library, an example <code>build.rs</code> script using the <a href="https://github.com/alexcrichton/cc-rs"><code>cc</code> crate</a> would look like this:</p> |
| <pre><code class="language-rust ignore">fn main() { |
| cc::Build::new() |
| .file("src/foo.c") |
| .compile("foo"); |
| }</code></pre> |
| <p>The <code>build.rs</code> is placed at the root of the package. Then <code>cargo build</code> will compile and execute it before the build of the package. A static archive named <code>libfoo.a</code> is generated and placed in the <code>target</code> directory.</p> |
| |
| </main> |
| |
| <nav class="nav-wrapper" aria-label="Page navigation"> |
| <!-- Mobile navigation buttons --> |
| <a rel="prev" href="../interoperability/index.html" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left"> |
| <i class="fa fa-angle-left"></i> |
| </a> |
| |
| <a rel="next prefetch" href="../interoperability/rust-with-c.html" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right"> |
| <i class="fa fa-angle-right"></i> |
| </a> |
| |
| <div style="clear: both"></div> |
| </nav> |
| </div> |
| </div> |
| |
| <nav class="nav-wide-wrapper" aria-label="Page navigation"> |
| <a rel="prev" href="../interoperability/index.html" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left"> |
| <i class="fa fa-angle-left"></i> |
| </a> |
| |
| <a rel="next prefetch" href="../interoperability/rust-with-c.html" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right"> |
| <i class="fa fa-angle-right"></i> |
| </a> |
| </nav> |
| |
| </div> |
| |
| |
| |
| |
| <script> |
| window.playground_copyable = true; |
| </script> |
| |
| |
| <script src="../elasticlunr.min.js"></script> |
| <script src="../mark.min.js"></script> |
| <script src="../searcher.js"></script> |
| |
| <script src="../clipboard.min.js"></script> |
| <script src="../highlight.js"></script> |
| <script src="../book.js"></script> |
| |
| <!-- Custom JS scripts --> |
| |
| |
| </div> |
| </body> |
| </html> |