Sophie

Sophie

distrib > Mageia > 7 > armv7hl > media > core-release > by-pkgid > 0c2243f8a1696816431e7210e991fa52 > files > 13201

rust-doc-1.35.0-1.mga7.armv7hl.rpm

<!DOCTYPE HTML>
<html lang="en" class="sidebar-visible no-js">
    <head>
        <!-- Book generated using mdBook -->
        <meta charset="UTF-8">
        <title>FFI - </title>
        <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="theme-color" content="#ffffff" />

        <base href="">

        <link rel="stylesheet" href="book.css">
        <link href="https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800" rel="stylesheet" type="text/css">
        <link href="https://fonts.googleapis.com/css?family=Source+Code+Pro:500" rel="stylesheet" type="text/css">

        <link rel="shortcut icon" href="favicon.png">

        <!-- Font Awesome -->
        <link rel="stylesheet" href="_FontAwesome/css/font-awesome.css">

        <link rel="stylesheet" href="highlight.css">
        <link rel="stylesheet" href="tomorrow-night.css">
        <link rel="stylesheet" href="ayu-highlight.css">

        <!-- Custom theme stylesheets -->
        

        

    </head>
    <body class="light">
        <!-- Work around some values being stored in localStorage wrapped in quotes -->
        <script type="text/javascript">
            try {
                var theme = localStorage.getItem('mdbook-theme');
                var 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 type="text/javascript">
            var theme;
            try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { } 
            if (theme === null || theme === undefined) { theme = 'light'; }
            document.body.className = theme;
            document.querySelector('html').className = theme + ' js';
        </script>

        <!-- Hide / unhide sidebar before it is displayed -->
        <script type="text/javascript">
            var html = document.querySelector('html');
            var sidebar = 'hidden';
            if (document.body.clientWidth >= 1080) {
                try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
                sidebar = sidebar || 'visible';
            }
            html.classList.remove('sidebar-visible');
            html.classList.add("sidebar-" + sidebar);
        </script>

        <nav id="sidebar" class="sidebar" aria-label="Table of contents">
            <ol class="chapter"><li class="affix"><a href="README.html">Introduction</a></li><li><a href="meet-safe-and-unsafe.html"><strong aria-hidden="true">1.</strong> Meet Safe and Unsafe</a></li><li><ol class="section"><li><a href="safe-unsafe-meaning.html"><strong aria-hidden="true">1.1.</strong> How Safe and Unsafe Interact</a></li><li><a href="what-unsafe-does.html"><strong aria-hidden="true">1.2.</strong> What Unsafe Can Do</a></li><li><a href="working-with-unsafe.html"><strong aria-hidden="true">1.3.</strong> Working with Unsafe</a></li></ol></li><li><a href="data.html"><strong aria-hidden="true">2.</strong> Data Layout</a></li><li><ol class="section"><li><a href="repr-rust.html"><strong aria-hidden="true">2.1.</strong> repr(Rust)</a></li><li><a href="exotic-sizes.html"><strong aria-hidden="true">2.2.</strong> Exotically Sized Types</a></li><li><a href="other-reprs.html"><strong aria-hidden="true">2.3.</strong> Other reprs</a></li></ol></li><li><a href="ownership.html"><strong aria-hidden="true">3.</strong> Ownership</a></li><li><ol class="section"><li><a href="references.html"><strong aria-hidden="true">3.1.</strong> References</a></li><li><a href="aliasing.html"><strong aria-hidden="true">3.2.</strong> Aliasing</a></li><li><a href="lifetimes.html"><strong aria-hidden="true">3.3.</strong> Lifetimes</a></li><li><a href="lifetime-mismatch.html"><strong aria-hidden="true">3.4.</strong> Limits of Lifetimes</a></li><li><a href="lifetime-elision.html"><strong aria-hidden="true">3.5.</strong> Lifetime Elision</a></li><li><a href="unbounded-lifetimes.html"><strong aria-hidden="true">3.6.</strong> Unbounded Lifetimes</a></li><li><a href="hrtb.html"><strong aria-hidden="true">3.7.</strong> Higher-Rank Trait Bounds</a></li><li><a href="subtyping.html"><strong aria-hidden="true">3.8.</strong> Subtyping and Variance</a></li><li><a href="dropck.html"><strong aria-hidden="true">3.9.</strong> Drop Check</a></li><li><a href="phantom-data.html"><strong aria-hidden="true">3.10.</strong> PhantomData</a></li><li><a href="borrow-splitting.html"><strong aria-hidden="true">3.11.</strong> Splitting Borrows</a></li></ol></li><li><a href="conversions.html"><strong aria-hidden="true">4.</strong> Type Conversions</a></li><li><ol class="section"><li><a href="coercions.html"><strong aria-hidden="true">4.1.</strong> Coercions</a></li><li><a href="dot-operator.html"><strong aria-hidden="true">4.2.</strong> The Dot Operator</a></li><li><a href="casts.html"><strong aria-hidden="true">4.3.</strong> Casts</a></li><li><a href="transmutes.html"><strong aria-hidden="true">4.4.</strong> Transmutes</a></li></ol></li><li><a href="uninitialized.html"><strong aria-hidden="true">5.</strong> Uninitialized Memory</a></li><li><ol class="section"><li><a href="checked-uninit.html"><strong aria-hidden="true">5.1.</strong> Checked</a></li><li><a href="drop-flags.html"><strong aria-hidden="true">5.2.</strong> Drop Flags</a></li><li><a href="unchecked-uninit.html"><strong aria-hidden="true">5.3.</strong> Unchecked</a></li></ol></li><li><a href="obrm.html"><strong aria-hidden="true">6.</strong> Ownership Based Resource Management</a></li><li><ol class="section"><li><a href="constructors.html"><strong aria-hidden="true">6.1.</strong> Constructors</a></li><li><a href="destructors.html"><strong aria-hidden="true">6.2.</strong> Destructors</a></li><li><a href="leaking.html"><strong aria-hidden="true">6.3.</strong> Leaking</a></li></ol></li><li><a href="unwinding.html"><strong aria-hidden="true">7.</strong> Unwinding</a></li><li><ol class="section"><li><a href="exception-safety.html"><strong aria-hidden="true">7.1.</strong> Exception Safety</a></li><li><a href="poisoning.html"><strong aria-hidden="true">7.2.</strong> Poisoning</a></li></ol></li><li><a href="concurrency.html"><strong aria-hidden="true">8.</strong> Concurrency</a></li><li><ol class="section"><li><a href="races.html"><strong aria-hidden="true">8.1.</strong> Races</a></li><li><a href="send-and-sync.html"><strong aria-hidden="true">8.2.</strong> Send and Sync</a></li><li><a href="atomics.html"><strong aria-hidden="true">8.3.</strong> Atomics</a></li></ol></li><li><a href="vec.html"><strong aria-hidden="true">9.</strong> Implementing Vec</a></li><li><ol class="section"><li><a href="vec-layout.html"><strong aria-hidden="true">9.1.</strong> Layout</a></li><li><a href="vec-alloc.html"><strong aria-hidden="true">9.2.</strong> Allocating</a></li><li><a href="vec-push-pop.html"><strong aria-hidden="true">9.3.</strong> Push and Pop</a></li><li><a href="vec-dealloc.html"><strong aria-hidden="true">9.4.</strong> Deallocating</a></li><li><a href="vec-deref.html"><strong aria-hidden="true">9.5.</strong> Deref</a></li><li><a href="vec-insert-remove.html"><strong aria-hidden="true">9.6.</strong> Insert and Remove</a></li><li><a href="vec-into-iter.html"><strong aria-hidden="true">9.7.</strong> IntoIter</a></li><li><a href="vec-raw.html"><strong aria-hidden="true">9.8.</strong> RawVec</a></li><li><a href="vec-drain.html"><strong aria-hidden="true">9.9.</strong> Drain</a></li><li><a href="vec-zsts.html"><strong aria-hidden="true">9.10.</strong> Handling Zero-Sized Types</a></li><li><a href="vec-final.html"><strong aria-hidden="true">9.11.</strong> Final Code</a></li></ol></li><li><a href="arc-and-mutex.html"><strong aria-hidden="true">10.</strong> Implementing Arc and Mutex</a></li><li><a href="ffi.html" class="active"><strong aria-hidden="true">11.</strong> FFI</a></li><li><a href="beneath-std.html"><strong aria-hidden="true">12.</strong> Beneath std</a></li><li><ol class="section"><li><a href="panic-handler.html"><strong aria-hidden="true">12.1.</strong> #[panic_handler]</a></li></ol></li></ol>
        </nav>

        <div id="page-wrapper" class="page-wrapper">

            <div class="page">
                
                <div id="menu-bar" class="menu-bar">
                    <div id="menu-bar-sticky-container">
                        <div class="left-buttons">
                            <button id="sidebar-toggle" class="icon-button" type="button" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
                                <i class="fa fa-bars"></i>
                            </button>
                            <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="light">Light <span class="default">(default)</span></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. (Shortkey: s)" 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"></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>
                        </div>
                    </div>
                </div>

                
                <div id="search-wrapper" class="hidden">
                    <form id="searchbar-outer" class="searchbar-outer">
                        <input type="search" name="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 type="text/javascript">
                    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>
                        <a class="header" href="ffi.html#foreign-function-interface" id="foreign-function-interface"><h1>Foreign Function Interface</h1></a>
<a class="header" href="ffi.html#introduction" id="introduction"><h1>Introduction</h1></a>
<p>This guide will use the <a href="https://github.com/google/snappy">snappy</a>
compression/decompression library as an introduction to writing bindings for
foreign code. Rust is currently unable to call directly into a C++ library, but
snappy includes a C interface (documented in
<a href="https://github.com/google/snappy/blob/master/snappy-c.h"><code>snappy-c.h</code></a>).</p>
<a class="header" href="ffi.html#a-note-about-libc" id="a-note-about-libc"><h2>A note about libc</h2></a>
<p>Many of these examples use <a href="https://crates.io/crates/libc">the <code>libc</code> crate</a>, which provides various
type definitions for C types, among other things. If you’re trying these
examples yourself, you’ll need to add <code>libc</code> to your <code>Cargo.toml</code>:</p>
<pre><code class="language-toml">[dependencies]
libc = &quot;0.2.0&quot;
</code></pre>
<p>and add <code>extern crate libc;</code> to your crate root.</p>
<a class="header" href="ffi.html#calling-foreign-functions" id="calling-foreign-functions"><h2>Calling foreign functions</h2></a>
<p>The following is a minimal example of calling a foreign function which will
compile if snappy is installed:</p>
<pre><code class="language-rust ignore">extern crate libc;
use libc::size_t;

#[link(name = &quot;snappy&quot;)]
extern {
    fn snappy_max_compressed_length(source_length: size_t) -&gt; size_t;
}

fn main() {
    let x = unsafe { snappy_max_compressed_length(100) };
    println!(&quot;max compressed length of a 100 byte buffer: {}&quot;, x);
}
</code></pre>
<p>The <code>extern</code> block is a list of function signatures in a foreign library, in
this case with the platform's C ABI. The <code>#[link(...)]</code> attribute is used to
instruct the linker to link against the snappy library so the symbols are
resolved.</p>
<p>Foreign functions are assumed to be unsafe so calls to them need to be wrapped
with <code>unsafe {}</code> as a promise to the compiler that everything contained within
truly is safe. C libraries often expose interfaces that aren't thread-safe, and
almost any function that takes a pointer argument isn't valid for all possible
inputs since the pointer could be dangling, and raw pointers fall outside of
Rust's safe memory model.</p>
<p>When declaring the argument types to a foreign function, the Rust compiler
cannot check if the declaration is correct, so specifying it correctly is part
of keeping the binding correct at runtime.</p>
<p>The <code>extern</code> block can be extended to cover the entire snappy API:</p>
<pre><code class="language-rust ignore">extern crate libc;
use libc::{c_int, size_t};

#[link(name = &quot;snappy&quot;)]
extern {
    fn snappy_compress(input: *const u8,
                       input_length: size_t,
                       compressed: *mut u8,
                       compressed_length: *mut size_t) -&gt; c_int;
    fn snappy_uncompress(compressed: *const u8,
                         compressed_length: size_t,
                         uncompressed: *mut u8,
                         uncompressed_length: *mut size_t) -&gt; c_int;
    fn snappy_max_compressed_length(source_length: size_t) -&gt; size_t;
    fn snappy_uncompressed_length(compressed: *const u8,
                                  compressed_length: size_t,
                                  result: *mut size_t) -&gt; c_int;
    fn snappy_validate_compressed_buffer(compressed: *const u8,
                                         compressed_length: size_t) -&gt; c_int;
}
# fn main() {}
</code></pre>
<a class="header" href="ffi.html#creating-a-safe-interface" id="creating-a-safe-interface"><h1>Creating a safe interface</h1></a>
<p>The raw C API needs to be wrapped to provide memory safety and make use of higher-level concepts
like vectors. A library can choose to expose only the safe, high-level interface and hide the unsafe
internal details.</p>
<p>Wrapping the functions which expect buffers involves using the <code>slice::raw</code> module to manipulate Rust
vectors as pointers to memory. Rust's vectors are guaranteed to be a contiguous block of memory. The
length is the number of elements currently contained, and the capacity is the total size in elements of
the allocated memory. The length is less than or equal to the capacity.</p>
<pre><code class="language-rust ignore"># extern crate libc;
# use libc::{c_int, size_t};
# unsafe fn snappy_validate_compressed_buffer(_: *const u8, _: size_t) -&gt; c_int { 0 }
# fn main() {}
pub fn validate_compressed_buffer(src: &amp;[u8]) -&gt; bool {
    unsafe {
        snappy_validate_compressed_buffer(src.as_ptr(), src.len() as size_t) == 0
    }
}
</code></pre>
<p>The <code>validate_compressed_buffer</code> wrapper above makes use of an <code>unsafe</code> block, but it makes the
guarantee that calling it is safe for all inputs by leaving off <code>unsafe</code> from the function
signature.</p>
<p>The <code>snappy_compress</code> and <code>snappy_uncompress</code> functions are more complex, since a buffer has to be
allocated to hold the output too.</p>
<p>The <code>snappy_max_compressed_length</code> function can be used to allocate a vector with the maximum
required capacity to hold the compressed output. The vector can then be passed to the
<code>snappy_compress</code> function as an output parameter. An output parameter is also passed to retrieve
the true length after compression for setting the length.</p>
<pre><code class="language-rust ignore"># extern crate libc;
# use libc::{size_t, c_int};
# unsafe fn snappy_compress(a: *const u8, b: size_t, c: *mut u8,
#                           d: *mut size_t) -&gt; c_int { 0 }
# unsafe fn snappy_max_compressed_length(a: size_t) -&gt; size_t { a }
# fn main() {}
pub fn compress(src: &amp;[u8]) -&gt; Vec&lt;u8&gt; {
    unsafe {
        let srclen = src.len() as size_t;
        let psrc = src.as_ptr();

        let mut dstlen = snappy_max_compressed_length(srclen);
        let mut dst = Vec::with_capacity(dstlen as usize);
        let pdst = dst.as_mut_ptr();

        snappy_compress(psrc, srclen, pdst, &amp;mut dstlen);
        dst.set_len(dstlen as usize);
        dst
    }
}
</code></pre>
<p>Decompression is similar, because snappy stores the uncompressed size as part of the compression
format and <code>snappy_uncompressed_length</code> will retrieve the exact buffer size required.</p>
<pre><code class="language-rust ignore"># extern crate libc;
# use libc::{size_t, c_int};
# unsafe fn snappy_uncompress(compressed: *const u8,
#                             compressed_length: size_t,
#                             uncompressed: *mut u8,
#                             uncompressed_length: *mut size_t) -&gt; c_int { 0 }
# unsafe fn snappy_uncompressed_length(compressed: *const u8,
#                                      compressed_length: size_t,
#                                      result: *mut size_t) -&gt; c_int { 0 }
# fn main() {}
pub fn uncompress(src: &amp;[u8]) -&gt; Option&lt;Vec&lt;u8&gt;&gt; {
    unsafe {
        let srclen = src.len() as size_t;
        let psrc = src.as_ptr();

        let mut dstlen: size_t = 0;
        snappy_uncompressed_length(psrc, srclen, &amp;mut dstlen);

        let mut dst = Vec::with_capacity(dstlen as usize);
        let pdst = dst.as_mut_ptr();

        if snappy_uncompress(psrc, srclen, pdst, &amp;mut dstlen) == 0 {
            dst.set_len(dstlen as usize);
            Some(dst)
        } else {
            None // SNAPPY_INVALID_INPUT
        }
    }
}
</code></pre>
<p>Then, we can add some tests to show how to use them.</p>
<pre><code class="language-rust ignore"># extern crate libc;
# use libc::{c_int, size_t};
# unsafe fn snappy_compress(input: *const u8,
#                           input_length: size_t,
#                           compressed: *mut u8,
#                           compressed_length: *mut size_t)
#                           -&gt; c_int { 0 }
# unsafe fn snappy_uncompress(compressed: *const u8,
#                             compressed_length: size_t,
#                             uncompressed: *mut u8,
#                             uncompressed_length: *mut size_t)
#                             -&gt; c_int { 0 }
# unsafe fn snappy_max_compressed_length(source_length: size_t) -&gt; size_t { 0 }
# unsafe fn snappy_uncompressed_length(compressed: *const u8,
#                                      compressed_length: size_t,
#                                      result: *mut size_t)
#                                      -&gt; c_int { 0 }
# unsafe fn snappy_validate_compressed_buffer(compressed: *const u8,
#                                             compressed_length: size_t)
#                                             -&gt; c_int { 0 }
# fn main() { }

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn valid() {
        let d = vec![0xde, 0xad, 0xd0, 0x0d];
        let c: &amp;[u8] = &amp;compress(&amp;d);
        assert!(validate_compressed_buffer(c));
        assert!(uncompress(c) == Some(d));
    }

    #[test]
    fn invalid() {
        let d = vec![0, 0, 0, 0];
        assert!(!validate_compressed_buffer(&amp;d));
        assert!(uncompress(&amp;d).is_none());
    }

    #[test]
    fn empty() {
        let d = vec![];
        assert!(!validate_compressed_buffer(&amp;d));
        assert!(uncompress(&amp;d).is_none());
        let c = compress(&amp;d);
        assert!(validate_compressed_buffer(&amp;c));
        assert!(uncompress(&amp;c) == Some(d));
    }
}
</code></pre>
<a class="header" href="ffi.html#destructors" id="destructors"><h1>Destructors</h1></a>
<p>Foreign libraries often hand off ownership of resources to the calling code.
When this occurs, we must use Rust's destructors to provide safety and guarantee
the release of these resources (especially in the case of panic).</p>
<p>For more about destructors, see the <a href="../std/ops/trait.Drop.html">Drop trait</a>.</p>
<a class="header" href="ffi.html#callbacks-from-c-code-to-rust-functions" id="callbacks-from-c-code-to-rust-functions"><h1>Callbacks from C code to Rust functions</h1></a>
<p>Some external libraries require the usage of callbacks to report back their
current state or intermediate data to the caller.
It is possible to pass functions defined in Rust to an external library.
The requirement for this is that the callback function is marked as <code>extern</code>
with the correct calling convention to make it callable from C code.</p>
<p>The callback function can then be sent through a registration call
to the C library and afterwards be invoked from there.</p>
<p>A basic example is:</p>
<p>Rust code:</p>
<pre><pre class="playpen"><code class="language-rust no_run">extern fn callback(a: i32) {
    println!(&quot;I'm called from C with value {0}&quot;, a);
}

#[link(name = &quot;extlib&quot;)]
extern {
   fn register_callback(cb: extern fn(i32)) -&gt; i32;
   fn trigger_callback();
}

fn main() {
    unsafe {
        register_callback(callback);
        trigger_callback(); // Triggers the callback.
    }
}
</code></pre></pre>
<p>C code:</p>
<pre><code class="language-c">typedef void (*rust_callback)(int32_t);
rust_callback cb;

int32_t register_callback(rust_callback callback) {
    cb = callback;
    return 1;
}

void trigger_callback() {
  cb(7); // Will call callback(7) in Rust.
}
</code></pre>
<p>In this example Rust's <code>main()</code> will call <code>trigger_callback()</code> in C,
which would, in turn, call back to <code>callback()</code> in Rust.</p>
<a class="header" href="ffi.html#targeting-callbacks-to-rust-objects" id="targeting-callbacks-to-rust-objects"><h2>Targeting callbacks to Rust objects</h2></a>
<p>The former example showed how a global function can be called from C code.
However it is often desired that the callback is targeted to a special
Rust object. This could be the object that represents the wrapper for the
respective C object.</p>
<p>This can be achieved by passing a raw pointer to the object down to the
C library. The C library can then include the pointer to the Rust object in
the notification. This will allow the callback to unsafely access the
referenced Rust object.</p>
<p>Rust code:</p>
<pre><pre class="playpen"><code class="language-rust no_run">#[repr(C)]
struct RustObject {
    a: i32,
    // Other members...
}

extern &quot;C&quot; fn callback(target: *mut RustObject, a: i32) {
    println!(&quot;I'm called from C with value {0}&quot;, a);
    unsafe {
        // Update the value in RustObject with the value received from the callback:
        (*target).a = a;
    }
}

#[link(name = &quot;extlib&quot;)]
extern {
   fn register_callback(target: *mut RustObject,
                        cb: extern fn(*mut RustObject, i32)) -&gt; i32;
   fn trigger_callback();
}

fn main() {
    // Create the object that will be referenced in the callback:
    let mut rust_object = Box::new(RustObject { a: 5 });

    unsafe {
        register_callback(&amp;mut *rust_object, callback);
        trigger_callback();
    }
}
</code></pre></pre>
<p>C code:</p>
<pre><code class="language-c">typedef void (*rust_callback)(void*, int32_t);
void* cb_target;
rust_callback cb;

int32_t register_callback(void* callback_target, rust_callback callback) {
    cb_target = callback_target;
    cb = callback;
    return 1;
}

void trigger_callback() {
  cb(cb_target, 7); // Will call callback(&amp;rustObject, 7) in Rust.
}
</code></pre>
<a class="header" href="ffi.html#asynchronous-callbacks" id="asynchronous-callbacks"><h2>Asynchronous callbacks</h2></a>
<p>In the previously given examples the callbacks are invoked as a direct reaction
to a function call to the external C library.
The control over the current thread is switched from Rust to C to Rust for the
execution of the callback, but in the end the callback is executed on the
same thread that called the function which triggered the callback.</p>
<p>Things get more complicated when the external library spawns its own threads
and invokes callbacks from there.
In these cases access to Rust data structures inside the callbacks is
especially unsafe and proper synchronization mechanisms must be used.
Besides classical synchronization mechanisms like mutexes, one possibility in
Rust is to use channels (in <code>std::sync::mpsc</code>) to forward data from the C
thread that invoked the callback into a Rust thread.</p>
<p>If an asynchronous callback targets a special object in the Rust address space
it is also absolutely necessary that no more callbacks are performed by the
C library after the respective Rust object gets destroyed.
This can be achieved by unregistering the callback in the object's
destructor and designing the library in a way that guarantees that no
callback will be performed after deregistration.</p>
<a class="header" href="ffi.html#linking" id="linking"><h1>Linking</h1></a>
<p>The <code>link</code> attribute on <code>extern</code> blocks provides the basic building block for
instructing rustc how it will link to native libraries. There are two accepted
forms of the link attribute today:</p>
<ul>
<li><code>#[link(name = &quot;foo&quot;)]</code></li>
<li><code>#[link(name = &quot;foo&quot;, kind = &quot;bar&quot;)]</code></li>
</ul>
<p>In both of these cases, <code>foo</code> is the name of the native library that we're
linking to, and in the second case <code>bar</code> is the type of native library that the
compiler is linking to. There are currently three known types of native
libraries:</p>
<ul>
<li>Dynamic - <code>#[link(name = &quot;readline&quot;)]</code></li>
<li>Static - <code>#[link(name = &quot;my_build_dependency&quot;, kind = &quot;static&quot;)]</code></li>
<li>Frameworks - <code>#[link(name = &quot;CoreFoundation&quot;, kind = &quot;framework&quot;)]</code></li>
</ul>
<p>Note that frameworks are only available on macOS targets.</p>
<p>The different <code>kind</code> values are meant to differentiate how the native library
participates in linkage. From a linkage perspective, the Rust compiler creates
two flavors of artifacts: partial (rlib/staticlib) and final (dylib/binary).
Native dynamic library and framework dependencies are propagated to the final
artifact boundary, while static library dependencies are not propagated at
all, because the static libraries are integrated directly into the subsequent
artifact.</p>
<p>A few examples of how this model can be used are:</p>
<ul>
<li>
<p>A native build dependency. Sometimes some C/C++ glue is needed when writing
some Rust code, but distribution of the C/C++ code in a library format is
a burden. In this case, the code will be archived into <code>libfoo.a</code> and then the
Rust crate would declare a dependency via <code>#[link(name = &quot;foo&quot;, kind = &quot;static&quot;)]</code>.</p>
<p>Regardless of the flavor of output for the crate, the native static library
will be included in the output, meaning that distribution of the native static
library is not necessary.</p>
</li>
<li>
<p>A normal dynamic dependency. Common system libraries (like <code>readline</code>) are
available on a large number of systems, and often a static copy of these
libraries cannot be found. When this dependency is included in a Rust crate,
partial targets (like rlibs) will not link to the library, but when the rlib
is included in a final target (like a binary), the native library will be
linked in.</p>
</li>
</ul>
<p>On macOS, frameworks behave with the same semantics as a dynamic library.</p>
<a class="header" href="ffi.html#unsafe-blocks" id="unsafe-blocks"><h1>Unsafe blocks</h1></a>
<p>Some operations, like dereferencing raw pointers or calling functions that have been marked
unsafe are only allowed inside unsafe blocks. Unsafe blocks isolate unsafety and are a promise to
the compiler that the unsafety does not leak out of the block.</p>
<p>Unsafe functions, on the other hand, advertise it to the world. An unsafe function is written like
this:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
unsafe fn kaboom(ptr: *const i32) -&gt; i32 { *ptr }
#}</code></pre></pre>
<p>This function can only be called from an <code>unsafe</code> block or another <code>unsafe</code> function.</p>
<a class="header" href="ffi.html#accessing-foreign-globals" id="accessing-foreign-globals"><h1>Accessing foreign globals</h1></a>
<p>Foreign APIs often export a global variable which could do something like track
global state. In order to access these variables, you declare them in <code>extern</code>
blocks with the <code>static</code> keyword:</p>
<pre><code class="language-rust ignore">extern crate libc;

#[link(name = &quot;readline&quot;)]
extern {
    static rl_readline_version: libc::c_int;
}

fn main() {
    println!(&quot;You have readline version {} installed.&quot;,
             unsafe { rl_readline_version as i32 });
}
</code></pre>
<p>Alternatively, you may need to alter global state provided by a foreign
interface. To do this, statics can be declared with <code>mut</code> so we can mutate
them.</p>
<pre><code class="language-rust ignore">extern crate libc;

use std::ffi::CString;
use std::ptr;

#[link(name = &quot;readline&quot;)]
extern {
    static mut rl_prompt: *const libc::c_char;
}

fn main() {
    let prompt = CString::new(&quot;[my-awesome-shell] $&quot;).unwrap();
    unsafe {
        rl_prompt = prompt.as_ptr();

        println!(&quot;{:?}&quot;, rl_prompt);

        rl_prompt = ptr::null();
    }
}
</code></pre>
<p>Note that all interaction with a <code>static mut</code> is unsafe, both reading and
writing. Dealing with global mutable state requires a great deal of care.</p>
<a class="header" href="ffi.html#foreign-calling-conventions" id="foreign-calling-conventions"><h1>Foreign calling conventions</h1></a>
<p>Most foreign code exposes a C ABI, and Rust uses the platform's C calling convention by default when
calling foreign functions. Some foreign functions, most notably the Windows API, use other calling
conventions. Rust provides a way to tell the compiler which convention to use:</p>
<pre><code class="language-rust ignore">extern crate libc;

#[cfg(all(target_os = &quot;win32&quot;, target_arch = &quot;x86&quot;))]
#[link(name = &quot;kernel32&quot;)]
#[allow(non_snake_case)]
extern &quot;stdcall&quot; {
    fn SetEnvironmentVariableA(n: *const u8, v: *const u8) -&gt; libc::c_int;
}
# fn main() { }
</code></pre>
<p>This applies to the entire <code>extern</code> block. The list of supported ABI constraints
are:</p>
<ul>
<li><code>stdcall</code></li>
<li><code>aapcs</code></li>
<li><code>cdecl</code></li>
<li><code>fastcall</code></li>
<li><code>vectorcall</code>
This is currently hidden behind the <code>abi_vectorcall</code> gate and is subject to change.</li>
<li><code>Rust</code></li>
<li><code>rust-intrinsic</code></li>
<li><code>system</code></li>
<li><code>C</code></li>
<li><code>win64</code></li>
<li><code>sysv64</code></li>
</ul>
<p>Most of the abis in this list are self-explanatory, but the <code>system</code> abi may
seem a little odd. This constraint selects whatever the appropriate ABI is for
interoperating with the target's libraries. For example, on win32 with a x86
architecture, this means that the abi used would be <code>stdcall</code>. On x86_64,
however, windows uses the <code>C</code> calling convention, so <code>C</code> would be used. This
means that in our previous example, we could have used <code>extern &quot;system&quot; { ... }</code>
to define a block for all windows systems, not only x86 ones.</p>
<a class="header" href="ffi.html#interoperability-with-foreign-code" id="interoperability-with-foreign-code"><h1>Interoperability with foreign code</h1></a>
<p>Rust guarantees that the layout of a <code>struct</code> is compatible with the platform's
representation in C only if the <code>#[repr(C)]</code> attribute is applied to it.
<code>#[repr(C, packed)]</code> can be used to lay out struct members without padding.
<code>#[repr(C)]</code> can also be applied to an enum.</p>
<p>Rust's owned boxes (<code>Box&lt;T&gt;</code>) use non-nullable pointers as handles which point
to the contained object. However, they should not be manually created because
they are managed by internal allocators. References can safely be assumed to be
non-nullable pointers directly to the type.  However, breaking the borrow
checking or mutability rules is not guaranteed to be safe, so prefer using raw
pointers (<code>*</code>) if that's needed because the compiler can't make as many
assumptions about them.</p>
<p>Vectors and strings share the same basic memory layout, and utilities are
available in the <code>vec</code> and <code>str</code> modules for working with C APIs. However,
strings are not terminated with <code>\0</code>. If you need a NUL-terminated string for
interoperability with C, you should use the <code>CString</code> type in the <code>std::ffi</code>
module.</p>
<p>The <a href="https://crates.io/crates/libc"><code>libc</code> crate on crates.io</a> includes type aliases and function
definitions for the C standard library in the <code>libc</code> module, and Rust links
against <code>libc</code> and <code>libm</code> by default.</p>
<a class="header" href="ffi.html#variadic-functions" id="variadic-functions"><h1>Variadic functions</h1></a>
<p>In C, functions can be 'variadic', meaning they accept a variable number of arguments. This can
be achieved in Rust by specifying <code>...</code> within the argument list of a foreign function declaration:</p>
<pre><code class="language-no_run">extern {
    fn foo(x: i32, ...);
}

fn main() {
    unsafe {
        foo(10, 20, 30, 40, 50);
    }
}
</code></pre>
<p>Normal Rust functions can <em>not</em> be variadic:</p>
<pre><code class="language-ignore">// This will not compile

fn foo(x: i32, ...) { }
</code></pre>
<a class="header" href="ffi.html#the-nullable-pointer-optimization" id="the-nullable-pointer-optimization"><h1>The &quot;nullable pointer optimization&quot;</h1></a>
<p>Certain Rust types are defined to never be <code>null</code>. This includes references (<code>&amp;T</code>,
<code>&amp;mut T</code>), boxes (<code>Box&lt;T&gt;</code>), and function pointers (<code>extern &quot;abi&quot; fn()</code>). When
interfacing with C, pointers that might be <code>null</code> are often used, which would seem to
require some messy <code>transmute</code>s and/or unsafe code to handle conversions to/from Rust types.
However, the language provides a workaround.</p>
<p>As a special case, an <code>enum</code> is eligible for the &quot;nullable pointer optimization&quot; if it contains
exactly two variants, one of which contains no data and the other contains a field of one of the
non-nullable types listed above.  This means no extra space is required for a discriminant; rather,
the empty variant is represented by putting a <code>null</code> value into the non-nullable field. This is
called an &quot;optimization&quot;, but unlike other optimizations it is guaranteed to apply to eligible
types.</p>
<p>The most common type that takes advantage of the nullable pointer optimization is <code>Option&lt;T&gt;</code>,
where <code>None</code> corresponds to <code>null</code>. So <code>Option&lt;extern &quot;C&quot; fn(c_int) -&gt; c_int&gt;</code> is a correct way
to represent a nullable function pointer using the C ABI (corresponding to the C type
<code>int (*)(int)</code>).</p>
<p>Here is a contrived example. Let's say some C library has a facility for registering a
callback, which gets called in certain situations. The callback is passed a function pointer
and an integer and it is supposed to run the function with the integer as a parameter. So
we have function pointers flying across the FFI boundary in both directions.</p>
<pre><code class="language-rust ignore">extern crate libc;
use libc::c_int;

# #[cfg(hidden)]
extern &quot;C&quot; {
    /// Registers the callback.
    fn register(cb: Option&lt;extern &quot;C&quot; fn(Option&lt;extern &quot;C&quot; fn(c_int) -&gt; c_int&gt;, c_int) -&gt; c_int&gt;);
}
# unsafe fn register(_: Option&lt;extern &quot;C&quot; fn(Option&lt;extern &quot;C&quot; fn(c_int) -&gt; c_int&gt;,
#                                            c_int) -&gt; c_int&gt;)
# {}

/// This fairly useless function receives a function pointer and an integer
/// from C, and returns the result of calling the function with the integer.
/// In case no function is provided, it squares the integer by default.
extern &quot;C&quot; fn apply(process: Option&lt;extern &quot;C&quot; fn(c_int) -&gt; c_int&gt;, int: c_int) -&gt; c_int {
    match process {
        Some(f) =&gt; f(int),
        None    =&gt; int * int
    }
}

fn main() {
    unsafe {
        register(Some(apply));
    }
}
</code></pre>
<p>And the code on the C side looks like this:</p>
<pre><code class="language-c">void register(void (*f)(void (*)(int), int)) {
    ...
}
</code></pre>
<p>No <code>transmute</code> required!</p>
<a class="header" href="ffi.html#calling-rust-code-from-c" id="calling-rust-code-from-c"><h1>Calling Rust code from C</h1></a>
<p>You may wish to compile Rust code in a way so that it can be called from C. This is
fairly easy, but requires a few things:</p>
<pre><pre class="playpen"><code class="language-rust">#[no_mangle]
pub extern fn hello_rust() -&gt; *const u8 {
    &quot;Hello, world!\0&quot;.as_ptr()
}
# fn main() {}
</code></pre></pre>
<p>The <code>extern</code> makes this function adhere to the C calling convention, as
discussed above in &quot;<a href="ffi.html#foreign-calling-conventions">Foreign Calling
Conventions</a>&quot;. The <code>no_mangle</code>
attribute turns off Rust's name mangling, so that it is easier to link to.</p>
<a class="header" href="ffi.html#ffi-and-panics" id="ffi-and-panics"><h1>FFI and panics</h1></a>
<p>It’s important to be mindful of <code>panic!</code>s when working with FFI. A <code>panic!</code>
across an FFI boundary is undefined behavior. If you’re writing code that may
panic, you should run it in a closure with <a href="../std/panic/fn.catch_unwind.html"><code>catch_unwind</code></a>:</p>
<pre><pre class="playpen"><code class="language-rust">use std::panic::catch_unwind;

#[no_mangle]
pub extern fn oh_no() -&gt; i32 {
    let result = catch_unwind(|| {
        panic!(&quot;Oops!&quot;);
    });
    match result {
        Ok(_) =&gt; 0,
        Err(_) =&gt; 1,
    }
}

fn main() {}
</code></pre></pre>
<p>Please note that <a href="../std/panic/fn.catch_unwind.html"><code>catch_unwind</code></a> will only catch unwinding panics, not
those who abort the process. See the documentation of <a href="../std/panic/fn.catch_unwind.html"><code>catch_unwind</code></a>
for more information.</p>
<a class="header" href="ffi.html#representing-opaque-structs" id="representing-opaque-structs"><h1>Representing opaque structs</h1></a>
<p>Sometimes, a C library wants to provide a pointer to something, but not let you
know the internal details of the thing it wants. The simplest way is to use a
<code>void *</code> argument:</p>
<pre><code class="language-c">void foo(void *arg);
void bar(void *arg);
</code></pre>
<p>We can represent this in Rust with the <code>c_void</code> type:</p>
<pre><code class="language-rust ignore">extern crate libc;

extern &quot;C&quot; {
    pub fn foo(arg: *mut libc::c_void);
    pub fn bar(arg: *mut libc::c_void);
}
# fn main() {}
</code></pre>
<p>This is a perfectly valid way of handling the situation. However, we can do a bit
better. To solve this, some C libraries will instead create a <code>struct</code>, where
the details and memory layout of the struct are private. This gives some amount
of type safety. These structures are called ‘opaque’. Here’s an example, in C:</p>
<pre><code class="language-c">struct Foo; /* Foo is a structure, but its contents are not part of the public interface */
struct Bar;
void foo(struct Foo *arg);
void bar(struct Bar *arg);
</code></pre>
<p>To do this in Rust, let’s create our own opaque types:</p>
<pre><pre class="playpen"><code class="language-rust">#[repr(C)] pub struct Foo { _private: [u8; 0] }
#[repr(C)] pub struct Bar { _private: [u8; 0] }

extern &quot;C&quot; {
    pub fn foo(arg: *mut Foo);
    pub fn bar(arg: *mut Bar);
}
# fn main() {}
</code></pre></pre>
<p>By including a private field and no constructor,
we create an opaque type that we can't instantiate outside of this module.
(A struct with no field could be instantiated by anyone.)
We also want to use this type in FFI, so we have to add <code>#[repr(C)]</code>.
And to avoid warning around using <code>()</code> in FFI, we instead use an empty array,
which works just as well as an empty type but is FFI-compatible.</p>
<p>But because our <code>Foo</code> and <code>Bar</code> types are
different, we’ll get type safety between the two of them, so we cannot
accidentally pass a pointer to <code>Foo</code> to <code>bar()</code>.</p>
<p>Notice that it is a really bad idea to use an empty enum as FFI type.
The compiler relies on empty enums being uninhabited, so handling values of type
<code>&amp;Empty</code> is a huge footgun and can lead to buggy program behavior (by triggering
undefined behavior).</p>

                    </main>

                    <nav class="nav-wrapper" aria-label="Page navigation">
                        <!-- Mobile navigation buttons -->
                        
                            <a rel="prev" href="arc-and-mutex.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" href="beneath-std.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 href="arc-and-mutex.html" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
                        <i class="fa fa-angle-left"></i>
                    </a>
                

                
                    <a href="beneath-std.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 src="searchindex.js" type="text/javascript" charset="utf-8"></script>
        
        
        <script src="elasticlunr.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="mark.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="searcher.js" type="text/javascript" charset="utf-8"></script>
        

        <script src="clipboard.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="highlight.js" type="text/javascript" charset="utf-8"></script>
        <script src="book.js" type="text/javascript" charset="utf-8"></script>

        <!-- Custom JS scripts -->
        

    </body>
</html>