<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Aida Getoeva on Medium]]></title>
        <description><![CDATA[Stories by Aida Getoeva on Medium]]></description>
        <link>https://medium.com/@aidagetoeva?source=rss-b9d41c1d8f54------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Rb6da3EzaFB0du6a</url>
            <title>Stories by Aida Getoeva on Medium</title>
            <link>https://medium.com/@aidagetoeva?source=rss-b9d41c1d8f54------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 05:21:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aidagetoeva/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Async C++/Rust Interoperability]]></title>
            <link>https://medium.com/@aidagetoeva/async-c-rust-interoperability-39ece4cd3dcf?source=rss-b9d41c1d8f54------2</link>
            <guid isPermaLink="false">https://medium.com/p/39ece4cd3dcf</guid>
            <dc:creator><![CDATA[Aida Getoeva]]></dc:creator>
            <pubDate>Wed, 03 Apr 2024 16:43:17 GMT</pubDate>
            <atom:updated>2025-08-11T20:55:17.855Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This article is a write-down of my talk for the </em><a href="https://www.rustnationuk.com/"><em>Rust Nation UK</em></a><em> 2024 conference.</em></p><h3>Motivation: Why C++?</h3><p>Rust seems like a great and safe alternative to C++. Desire to rewrite everything in Rust may be compelling: no foot-guns and all the benefits of a system programming language. However, there are many reasons why there is still a place for C++, let’s look at some of them:</p><ul><li><strong>Extra responsibilities.</strong> If there is a perfect solution out there, that is being actively developed and well supported, it’s very hard to find a reason for another one. Writing your own library, apart from the complexity of it, means taking all the responsibilities for maintaining and updating said library.</li><li><strong>New code, new bugs.</strong> Designing a new solution from scratch may solve some existing problems but bring many new ones.</li><li><strong>Limited resources.</strong> If there is not enough resource, it’s hard to justify why C++ -&gt; Rust rewrite is a good idea. Yes, it can potentially improve maintainability and reduce the tech-debt, but it will also bring negative short-term impact.</li></ul><h3>Interoperability Tools</h3><p>There are at least three main solutions for C++/Rust interoperability: Bindgen, CXX and cpp! We’ll focus on Bindgen and CXX, but the issues discussed below will most probably be relevant to any binding tool that doesn’t support seamless async.</p><p>Before we jump into the specifics, it’s important to keep in mind that C++ code is complex and neither of the mentioned tools is currently capable of correctly interpreting inheritance and heavy use of templates. That means Rust may not know the size and structure of some of the exposed C++ types and cannot pass them by value.</p><p><em>That said, there are reasons why you may choose CXX over Bindgen.</em></p><p><a href="https://github.com/rust-lang/rust-bindgen"><strong>Bindgen</strong></a></p><p>Being the oldest and most used tool on the market. Bindgen is capable of consuming whole C++ libraries, lists of header files and producing <em>extern “C”</em> code compatible with Rust.</p><ul><li>Supports seamless conversion between primitive types and raw pointers but not for the common complex types like string or vector.</li><li>No support for the C++ smart pointers means unsafe memory handling and lack of implicit destructors.</li><li>Bindgen doesn’t handle neither constructors nor destructors and frequently requires to write a C-like simplified API around the types and functions being exposed to Rust.</li><li>Generated <em>extern “C”</em> functions are unsafe.</li><li>Bindgen operates on a best-effort policy, meaning it handles huge amount of code in one go producing silent errors that lead to failures in runtime.</li></ul><p><a href="https://cxx.rs/index.html"><strong>CXX</strong></a></p><p>The idea behind CXX is to provide <em>safe</em> and idiomatic bindings without much overhead. It takes a bit more manual approach by requiring the engineer to explicitly specify types, functions and methods that need to be exposed between C++ and Rust in the special module called <em>cxx::bridge</em>.</p><ul><li>Supports seamless translation between vectors, strings and smart pointers.</li><li>The bridge provides a two-way road between C++ and Rust allowing to define types shared between both languages and types being exposed from Rust to C++ and vice versa.</li><li>CXX employs static analysis to check the external function signatures to provide <strong>safe</strong> external bindings, i.e. <em>extern “C” functions are safe</em>.</li><li>CXX does only what it’s told to do, no silent errors, no surprises.</li><li><strong>Smart pointers</strong>! The support of smart pointers reduces burden of watching memory safety to a minimum and basically eliminates most of the potential issues.</li></ul><h4>Binding examples</h4><p><em>You can find a comprehensive and easy to follow guide on CXX bindings </em><a href="https://cxx.rs/index.html"><em>here</em></a><em> and for Bindgen </em><a href="https://github.com/rust-lang/rust-bindgen"><em>here</em></a><em>.</em></p><p>Let’s assume that we want to bind a simple C++ library for Mysql. Here is how it can look like:</p><pre>// represents a connection to the DB, allows to run queries<br>class Connection; <br><br>// client allows to concurrently acquire connection to the DB<br>class MysqlClient {<br>    // address of the DB shard we&#39;re connecting to<br>    std::string shard_;<br><br>public:<br>    MysqlClient(const std::string db): shard_(db) {}<br>    ~MysqlClient();<br><br>    // connects to the DB and returns a Connection instance<br>    std::unique_ptr&lt;Connection&gt; connect_sync();<br>    <br>    // asynchronously connects to the DB<br>    folly::SemiFuture&lt;std::unique_ptr&lt;Connection&gt;&gt; connect();<br>};<br><br>// a simple wrapper that allows to create a client instance<br>// wrapped in the shared pointer<br>std::shared_ptr&lt;MysqlClient&gt; new_mysql_client(const std::string&amp; db) {<br>    return std::make_shared&lt;MysqlClient&gt;(db);<br>}</pre><p>That’s how Rust side can look like using CXX. <br>We will only expose <strong>synchronous</strong> code for now.</p><pre>#[cxx::bridge]<br>mod ffi {<br>    unsafe extern &quot;C&quot; {<br>        // opaque C++ types<br>        type MysqlClient;<br>        type Connection;<br> <br>        fn new_mysql_client(<br>            db: &amp;str<br>        ) -&gt; cxx::SharedPtr&lt;MysqlClient&gt;;<br><br>        // client member-function<br>        fn connect_sync(self: &amp;MysqlClient) -&gt; cxx::UniquePtr&lt;Connection&gt;;<br>    }<br>}<br><br>// a simple wrapper-type for the client<br>struct RustMysqlClient {<br>    inner: cxx::SharedPtr&lt;ffi::MysqlClient&gt;,<br>}<br><br>impl RustMysqlClient {<br>    fn new(db: &amp;str) -&gt; Self {<br>        Self {<br>            inner: ffi::new_mysql_client(db),<br>        }<br>    }<br><br>    fn connect(&amp;self) -&gt; cxx::UniquePtr&lt;ffi::Connection&gt; {<br>        self.inner.connect_sync()<br>    }<br>}</pre><h3>Async Programming</h3><p>Why asynchronous programming is tricky? What is so different between C++ and Rust async API that needs a special treatment?</p><p>Asynchronous function call is not just another sequential block of code we can run.<strong> </strong>It’s a task that is going to be executed at some point of time “independently” from the main flow of the program and concurrently to it and other tasks within the program. Let’s look at the specifics for C++ and Rust.</p><p><em>In the examples below I’m using </em><a href="https://github.com/facebook/folly"><em>Folly</em></a><em> (C++ library) and </em><a href="https://docs.rs/tokio/latest/tokio/"><em>Tokio</em></a><em> (Rust crate) for the async runtime, but the content of this article is library-agnostic.</em></p><p>In <strong>C++</strong> the result of an async function call is <strong>not</strong> a value, it’s a <strong>promise</strong> of a value. You can think of it like a container that is empty for now and is fulfilled as soon as the execution completes. The call immediately schedules a task to be executed but it doesn’t let you know how much time it’s actually going to take, instead it gives you an API to access the result when ready.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l1nQvFWIQL3eBpjGgypRqA.png" /></figure><p><strong>Async Rust</strong> works similarly in a way, but has one interesting difference: a call to the async function does <strong>not</strong> really promise you anything... just yet. The resulting object, a future, is not going to do much unless it’s specifically <em>polled</em>, for example, as a part of an <em>await</em> call. Only then it promises to complete and return the value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PVaVnLAOtK-KW19ZB6ZMDA.png" /></figure><p>The challenge within async bindings is in the fact that neither Rust nor C++ runtime is aware of the other one. And having concurrent tasks running in both of them we need to come up with a way to share the state of the futures across the runtime border.</p><h3>Running Async C++ from Rust</h3><p>The big question now is how do we make Rust and C++ runtimes talk?Assume we want to connect to the Mysql server using an async method:</p><pre>// async connect<br>folly::SemiFuture&lt;std::unique_ptr&lt;Connection&gt;&gt; <br>        MysqlClient::connect();</pre><p>As mentioned, a non-waiting call to the async C++ method will schedule the future to be executed, so let us do just that. Let’s make a sync call on the Rust side to the FFI <em>connect</em> and leave it at that.</p><p>What do we have now? There is a future on the C++ side that is trying to connect to Mysql, but we don’t have any idea when that will actually happen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l24agc9LhrspNl_UJENceQ.png" /><figcaption>We want to make Rust runtime be aware of the C++ future completion</figcaption></figure><p>A naive way to make it work is to expose C++ future type to Rust together with all the API necessary to poll the future and check for it’s completion. We can check if the future object is ready in a loop and sleep in between the calls. The problem though… it doesn’t feel very <em>asynchronous</em>.</p><p>The reason we’re dealing with async here is because we want it to keep async in Rust, for example, due to heavy IO within the program. We can make <em>sleep</em> async (see<em> </em><a href="https://docs.rs/tokio/latest/tokio/time/fn.sleep.html"><em>tokio::time::sleep</em></a>) which solves some of the problems, but not all. The amount of boilerplate and a not-so-sound way of communication makes tedious.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0hJasGEO8hoS5cbZqsqlfA.png" /><figcaption>One way to do it is using good old ready?-sleep! loop</figcaption></figure><p>Let’s now think about something out of a Computer Science class, more specifically inter-process communication. How would you implement a game of ping-pong between two processes? <br>That’s right, using a <strong>channel</strong>!</p><p>We can define an async channel on the Rust side and ask C++ to send the result of the future back through the channel. <a href="https://docs.rs/oneshot/latest/oneshot/fn.channel.html">Oneshot</a> is a good candidate to use, it allows to <em>synchronously</em> send a single message and <em>asynchronously</em> receive it.</p><p>This means, that from the Rust perspective, the first connect call will stay sync, while the async part’ll happen while waiting on the receiver!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MFrC9lH5-GfzGIU6Aj3qqQ.png" /><figcaption>I guess we could also use a pigeon post…</figcaption></figure><p><em>Now it’s time to talk about the “boring” stuff: how is it actually implemented?</em></p><p>As you may have noticed, C++ doesn’t know anything about the Rust channel type. And the fun thing: it <strong>doesn’t</strong> need to. We can define a couple of simple callbacks in Rust that will know how to talk to the channel and expose those callbacks to C++ as a couple of function-typed arguments.</p><pre>#[cxx::bridge]<br>mod ffi {<br>    extern &quot;Rust&quot; {<br>        type Transmitter;<br>    }<br><br>    unsafe extern &quot;C++&quot; {<br>        fn connect(<br>            client: SharedPtr&lt;MysqlClient&gt;,<br>            options: ConnectionOptions,<br>            ok: fn(Transmitter, UniquePtr&lt;Connection&gt;),<br>            fail: fn(Transmitter, &amp;CxxString),<br>            tx: Transmitter,<br>        ) -&gt; Result&lt;()&gt;;<br>    }<br>}<br><br>// result of the connect call with string as an Error type<br>struct ResultPayload(Result&lt;Connection, String&gt;);<br>// a simple wrapper for the sender part of the channel<br>type Transmitter = Box&lt;oneshot::Sender&lt;ResultPayload&gt;&gt;;<br><br>// callback in case of a successful result<br>fn ok(tx: Transmitter, conn: cxx::UniquePtr&lt;ffi::Connection&gt;) {<br>    let conn = Connection(conn);<br>    let _ = *tx.send(Ok(conn));<br>}<br><br>// callback in case of an exception<br>fn fail(tx: Transmitter, error: String) {<br>  let _ = *tx.send(Err(error));<br>}<br><br>// now we can async connect to Mysql<br>async fn connect(client: RustMysqlClient) -&gt; Result&lt;Connection, String&gt; {<br>    // create a channel<br>    let (tx, rx) = oneshot::channel();<br>    <br>    // sync connect to start the future execution<br>    ffi::connect(client, ok, fail, Box::new(tx))?;<br>    // async wait on the channel to get the future result back to Rust<br>    let ResultPayload(result) = rx.await?;<br><br>    result<br>}</pre><p>In C++ we have to implement a simple shim API that knows what to do with the callbacks:</p><pre>// definition for `ok` callback type<br>using OkCallback = ::rust::Fn&lt;void(<br>    ::rust::Box&lt;Transmitter&gt;, <br>    std::unique_ptr&lt;Connection&gt;<br>)&gt;;<br>// definition for `fail` callback type<br>using ErrCallback = ::rust::Fn&lt;void(<br>    ::rust::Box&lt;Transmitter&gt;,<br>    const std::string&amp;,<br>)&gt;;<br><br>void connect(<br>    const std::shared_ptr&lt;MysqlClient&gt;&amp; client,<br>    ConnectionOptions opts,<br>    OkCallback ok,<br>    ErrCallback fail,<br>    ::rust::Box&lt;Transmitter&gt; tx,<br>) {<br>    client-&gt;connect(options)<br>        .via(get_executor()) // schedule the future on the executor<br>        .thenTry([ok, fail, tx = std::move(tx)](auto&amp;&amp; res) mutable {<br>            if (res.hasValue()) {<br>                // successful result, let&#39;s send it back over the &#39;ok&#39;<br>                (*ok)(std::move(tx), res);<br>            } else {<br>                // not that successfule one...<br>                (*fail)(std::move(tx), &quot;Failed!&quot;);<br>            }<br>        });<br>}</pre><h3>Issues Within Async C++/Rust</h3><p>There wouldn’t be this talk here if things were all sunshine and roses :)<br>If I’ve ever got a segmentation fault in Rust it was while working on the async bindings for C++. So… let’s look at some of the things that may (and probably <em>will</em>) go wrong.</p><h4>Thread safety</h4><p><strong>Send</strong> and <strong>Sync</strong> traits represent two <a href="https://doc.rust-lang.org/nomicon/send-and-sync.html">fundamental concepts</a> in async Rust:</p><ul><li><strong><em>Send</em></strong> means the object is safe to <strong>send</strong> between threads.</li><li><strong><em>Sync</em></strong> means the object is safe to <strong>share</strong> between threads.</li></ul><p>Send/Sync are <strong>unsafe</strong> traits. Although they’re automatically derived for complex types consisting of Send/Sync primitives, there are times you have to make a decision <em>yourself </em>whether<em> </em>to implement or not the traits for your type.</p><p>Not having the type being Send/Sync still allows you to run async Rust code, but it significantly limits the ability to use async patterns. For example, not-Send types cannot be <a href="https://docs.rs/tokio/latest/tokio/task/fn.spawn.html">spawned</a> as a part of a task on another thread.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xzaPiKAAesONixlBkKo9rQ.png" /></figure><p>The tricky part within the bindings is that <strong>the engineer</strong> is <strong>fully responsible</strong> for figuring out whether the C++ type being exposed is <strong>Send </strong>and<strong> Sync safe</strong>.</p><p>Unfortunately, the only way out of this is to have a comprehensive understanding of the C++ code, or very good comments and some trust :)</p><p><em>It’s easy to copy-paste stuff, it is also common for the types to implement both Send and Sync traits. Keep in mind that it is not necessarily true.</em> <em>For example, a Mysql connection is perfectly Send-safe but definitely not Sync-safe.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dqjXJu2EyzxM30SmI4wuww.png" /><figcaption>Copy-paste bugs are the worst :/</figcaption></figure><h4>Lost pointers</h4><p>Now, let’s assume that either we’re using Bindgen that doesn’t support smart pointers, or the MysqlClient::connect(..) returns a raw pointer. Either way, we have to send a raw pointer over the channel.</p><p>What if the channel receiver drops before it reads the message? This can very well happen when you race multiple tasks and one of them decides to panic or when you set a time limit on the async task. The receiver is being destroyed, but not the C++ side. C++ still continues to execute the future and sends the result over the channel. Because the receiver is gone, the objects within the channel will be destroyed too.</p><p>So… what’s going to happen to the newly acquired connection object?<br>It’s <strong>leaked</strong>!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P2eOfQITR-W0zHECGYZ4YQ.png" /><figcaption>It goes straight into the abyss of leaked memory</figcaption></figure><p>The object within the channel is a raw pointer, meaning it’s just an address. Rust doesn’t know anything about it, neither size/structure nor which destructors should be used to free the memory. When the channel starts to unwind, the connection pointer will be destroyed but not the connection itself. Thus <strong>it’s leaked</strong>.</p><p>Apart from the memory leaking it can also lead to nasty <strong>deadlocks</strong>.</p><p><em>Connection pool</em> is a way to reuse connections to the server and save on the round-trips. If there is an open and free connection in the pool, it will be returned on connect(..). If all the connections are busy, connect(..) will wait until one gets freed.</p><p>Now, let’s assume we have a pool for two connections. We are trying to acquire two connections in a row, limiting each task to run max 5ms. If the connect(..) future takes more time to execute, it will be dropped before the connection is ready. Dropping the receiver and whatever is within the channel.</p><p>When we call connect(..) again, we’ll hit a <strong>deadlock</strong>: <em>all connections in the pool are leaked and not freed, meaning the pool still thinks they’re in use.</em></p><p>At this point we’ll be waiting either till one of the connection expires (if there is an expiration time set) or… forever (:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2IKUJqjIx6XQJzHti5kz6Q.png" /><figcaption>Deadlock on connection pool ☠️</figcaption></figure><p>How do we deal with it? <br><strong>Smart pointers. Smart pointers or explicit destructors</strong>:</p><ul><li><strong>If there is a way to use smart pointers, use them</strong>. When a smart pointer is being freed, it does call the destructor.</li><li>Otherwise (for example, in Bindgen), <strong>wrap the raw pointer into a struct that knows how to free the memory</strong>. You are required to expose the destructor and explicitly call it from the Drop::drop().</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p4yE9GEU5S4Mt4Tir9Re1A.png" /><figcaption>Be smart, drop things</figcaption></figure><h4>Lifetime issue</h4><p>Probably the most important feature of Rust is being memory safe. Objects in Rust are either exclusively owned, read-only shared or explicitly declared and safe for the write-read sharing.</p><p><em>What if C++ gets an access to an object owned exclusively by Rust?</em></p><p>Let’s consider this scenario. C++ connect(..) function takes a raw pointer to the client as an argument. Mysql client object is exclusively owned by Rust, it is Sync-safe and we would like to access the client and acquire multiple connections concurrently. That means we <strong>cannot</strong> give up on ownership when calling C++, but we must provide a pointer to C++ anyway.</p><pre>async fn connect(client: Arc&lt;MysqlClient&gt;) -&gt; Result&lt;Connection, Error&gt; {<br>    ffi::connect(client.as_ptr(), ok, fail)<br>    ...<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h4sJAbnc1p6HSghvHM0jjw.png" /><figcaption>C++ access the client object exclusively owned by Rust</figcaption></figure><p><em>What if Rust runtime starts to shut down? </em><br>The stack unwinds, the objects are being destroyed, the memory deallocated.</p><p>C++ runtime is <strong>not</strong> bound to Rust, if the connect future hasn’t finished the execution it will continue running until… until the client object suddenly<strong> goes away</strong>.</p><p><strong>SEGFAULT</strong>!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PolKTfgyR9WPQkSRceitqw.png" /><figcaption>Have you seen SEGFAULT in Rust? Now you have!</figcaption></figure><p>This happens because Rust thinks that it has an <strong>exclusive</strong> ownership over the client object, it is not aware of the C++ side using the client. On shut down, as the client users go away, the reference counter Arc&lt;..&gt; gets to 0 and the Mysql client within it gets freed.<br><strong>But it is still used by C++!</strong></p><p>How do we make it work?</p><p>Well… <strong>smart shared pointers</strong>! If it’s not possible (Bindgen), please read further :)</p><p>We need to fix the issue in the root of it: <em>bind Rust runtime to the C++ one</em>. Make Rust aware that client is used by C++ and extend its lifetime until C++ future is running. The easiest way to do that is to <strong>explicitly share a clone of object with C++</strong>. Meaning the reference counter will never gets to 0 while C++ future is still executing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TPp0UbRmnkiNY5a7tRk7jA.png" /><figcaption>Share things responsibly</figcaption></figure><p>You may think that this is not possible… how would C++ understand how to use Arc&lt;..&gt;? The answer, it cannot understand it and <strong>doesn’t</strong> need to. We can share a clone of the object just as a “luggage”, an additional weight with the only goal: <strong>to be alive until C++ is done with the future</strong>.</p><p>Basically, C++ will still take a raw pointer to the client, but as another argument it will receive a blob, a pointer to some Rust object (clone of Arc). C++ only needs to send this blob back to Rust over the channel as soon as it’s ready. Then Rust will free it and proceed with whatever it’s doing.</p><p><em>This is an example of Rust code sending a clone over to C++:</em></p><pre>async fn connect(client: Arc&lt;MysqlClient&gt;) -&gt; Result&lt;Connection, Error&gt; {<br>    let (tx, rx) = oneshot::channel();<br>    let context = Box::new((tx, client.clone()));<br><br>    ffi::connect(<br>        client.as_ptr(), <br>        Box::into_raw(context) as *mut c_void, <br>        ok, <br>        fail,<br>    )?;<br><br>    let ResultPayload(result, _context) = rx.await?;<br>    result<br>}</pre><h3>The End</h3><p>…and thus C++ and Rust lived happily ever after.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kmAy5dEywdW2kjp3yaaNjQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39ece4cd3dcf" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>