<?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 Teodor Ciuraru on Medium]]></title>
        <description><![CDATA[Stories by Teodor Ciuraru on Medium]]></description>
        <link>https://medium.com/@TeodorC?source=rss-87a0ced82a2e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*uWBJuqGoGlTFQbpsjo_cEQ.jpeg</url>
            <title>Stories by Teodor Ciuraru on Medium</title>
            <link>https://medium.com/@TeodorC?source=rss-87a0ced82a2e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 20:25:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@TeodorC/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[Bridging React Native and Rust via JSI]]></title>
            <link>https://medium.com/@TeodorC/bridging-react-native-and-rust-via-jsi-458df647f8fd?source=rss-87a0ced82a2e------2</link>
            <guid isPermaLink="false">https://medium.com/p/458df647f8fd</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[jsi]]></category>
            <category><![CDATA[sdk]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[Teodor Ciuraru]]></dc:creator>
            <pubDate>Mon, 17 Jun 2024 10:28:53 GMT</pubDate>
            <atom:updated>2024-06-17T10:50:01.674Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KFf7xTRuIgkfYVYA" /></figure><p>At Ditto, our mission is to help developers build incredible applications that can always view, edit, and move data across devices, even without access to Wi-Fi, servers, or the cloud. As we aim to make our platform accessible everywhere, one of our main objectives is to find solutions for extending our core product (written in Rust) to as many platforms and frameworks as possible. When I joined, Ditto was already available to various branches of the mobile ecosystem: <a href="https://docs.ditto.live/swift/installation">iOS</a>, <a href="https://docs.ditto.live/?_gl=1*95v0mp*_ga*MTMzMjU4NjYzNC4xNjkwODAzMzk2*_ga_D8PMW3CCL2*MTcwOTM4MjM0Ny4xODkuMS4xNzA5MzgzNzAwLjYwLjAuMA..#9GKiaLmKOXDIdNgKMVf8D">Android</a>, <a href="https://docs.ditto.live/cpp/installation">C++</a>, <a href="https://docs.ditto.live/?_gl=1*95v0mp*_ga*MTMzMjU4NjYzNC4xNjkwODAzMzk2*_ga_D8PMW3CCL2*MTcwOTM4MjM0Ny4xODkuMS4xNzA5MzgzNzAwLjYwLjAuMA..#gUlN2dd5hJnj0_JIH6e2A">JavaScript</a>, <a href="https://docs.ditto.live/csharp/installation">Xamarin</a> (.NET MAUI), and <a href="https://docs.ditto.live/rust/installation">Rust</a>. Given my previous mobile development experience, I was first tasked with creating the <a href="https://www.npmjs.com/package/@dittolive/ditto">Ditto React Native SDK</a>.</p><p>In this article, I’ll discuss how we approached building our React Native SDK and review the options we considered and ultimately landed on. I’ll then detail how we approached bridging our Rust core logic with React Native through JavaScript Interface (JSI). I’ll finally walk you through an example of creating a React Native module based on a template and setting it up to bridge a Rust library.</p><p>If you want to explore all the code in this article, you can do so at <a href="https://github.com/teodorciuraru/rn-jsi-rust-bridging">https://github.com/teodorciuraru/rn-jsi-rust-bridging</a>.</p><h3>Plan of action</h3><p>The team’s first step was exploring and deciding on the architectural options. We needed a way to expose the Rust core to JavaScript and do it efficiently. And bonus points for allowing cross-platform expansion! I was already familiar with React Native’s legacy and <a href="https://reactnative.dev/docs/the-new-architecture/landing-page">new architecture (TurboModules &amp; Fabric)</a> and considered both viable options, but we had to weigh their pros and cons. We narrowed down our findings to two primary options:</p><ol><li><strong>SDK-embedding design</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vsCs5A56wDVsbB5seR2wJw.png" /></figure><p>Integrating the current <a href="https://docs.ditto.live/v4-4/swift-installing">iOS</a> and <a href="https://docs.ditto.live/kotlin-installing">Android</a> SDKs under a native module (library) project would’ve given us the advantage of fast time-to-market and delegating development responsibilities to the underlying products. On the downside, it would’ve significantly increased the overhead due to the extra layers of indirection; moreover, it would’ve required more workarounds to extend to other platforms.</p><p><strong>2. “New Architecture” design</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iwTlBUl3b2lHQg86LK77aw.png" /></figure><p>Instead of embedding a minimum of two other SDKs, given React Native’s New Architecture, we could now create a <strong>platform-agnostic C++ layer</strong> that has Rust interoperability out-of-the-box and enables several cross-platform extensions (iOS, Android, macOS, Windows) with minimal additional overhead. The advantages of this approach are several:</p><ul><li>You can leverage <a href="https://reactnative.dev/docs/the-new-architecture/why">React Native’s New Architecture perks</a>.</li><li>You gain direct control over the SDK’s integration with the core module, minimizing layers of indirection. This control enhances communication efficiency between the core and your application. Still, it increases your team’s responsibilities, implying closer collaboration with the core team on API design and deeper involvement with C++.</li><li>Cross-platform is readily accessible and easier to maintain due to the single source-of-truth C++ base. The <strong>New Architecture</strong> approach was a clear winner but wasn’t free of tradeoffs. The primary disadvantage was that switching to TurboModules increased backward compatibility complexity with legacy architecture apps. Another disadvantage would be its learning curve, but we approached the switch as a long-term investment and decided that the time expenditure was worth it.</li></ul><blockquote><em>💡</em> <em>To amend the backward compatibility issue, we decided to only use the </em><strong><em>JSI component of the new architecture in conjunction with legacy Native Modules</em></strong><em>. This allows us to keep most of the new architecture’s advantages and accept full architectural compatibility (Native Modules are forward-compatible 👌) while dismissing the TurboModules initialization time performance boost. This seems to be non-significant for our case.</em></blockquote><p>Although the strategy was clear, the groundwork laid by the JavaScript (JS) SDK hinted at another advantageous improvement, uncovering an extra architectural option for us.</p><h3>Leveraging the JavaScript SDK’s implementation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XBySosl6zdIFCKUsHhLZxA.png" /></figure><p>The JS team was already bridging Rust logic through WebAssembly (wasm-bindgen) and Node (Node-API). It was only natural for us to continue with this approach, treating the React Native project as another extension of the JavaScript SDK and reusing most of the codebase by building over the unified groundwork that was already in place. By plugging in the React Native slice, we can access the JS SDK&#39;s codebase (tests included!) while duplicating logic at a minimum. With the right abstractions and minimal bridging, we&#39;ll see that we can create a full-fledged React Native SDK only by typing in JSI C++ marshaling methods.</p><h3>Creating a React Native SDK JSI project</h3><h3>Scaffolding</h3><p>You can quickly assemble a <a href="https://reactnative.dev/docs/native-modules-setup">React Native library project</a> starting point via:</p><pre>npx create-react-native-library@latest react-native-jsi-module</pre><p>Be sure to enter your project details and select the Native Module &gt; C++ for Android &amp; iOS template, as this is the closest to our intended setup.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B3y34c8eF-TzIuzE4n2ckQ.png" /></figure><p>We explored the folder structure and saw that it created the connections to call C++ code. Still, the project is not currently using JSI but calling the low-level code via the iOS and Android platforms’ interoperability features. iOS supports C++ through Objective-C, while Android uses Java Native Interface (JNI) to call into the contents of the cpp folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Vj4jjF-HCcFly7xo8ElAw.png" /></figure><p>Next, we will explore how to model the project structure to integrate JSI for enhanced performance (reducing the bridging serialization bottleneck, unified memory management), synchronous calls, and aligning your app for the New Architecture. To do this, we will write our sample multiply() function in C++, configure JSI for iOS and Android subprojects and see the results in JavaScript.</p><h3>C++</h3><p>Inside cpp/react-native-jsi-module.h we will expose bridgeJSIFunctions():</p><pre>// cpp/react-native-jsi-module.h<br><br>#ifndef JSIMODULE_H<br>#define JSIMODULE_H<br><br>// iOS has the JSI module included out-of-the-box through Pods, <br>// while Android will include it using `CMakeLists.txt`.<br>#include &lt;jsi/jsi.h&gt;<br><br>using namespace facebook::jsi;<br><br>namespace jsimodule {<br> void bridgeJSIFunctions(Runtime &amp;jsi);<br>}<br><br>#endif /* JSIMODULE_H */</pre><p>We then modify the default multiply function and rewrite it under JSI parlance in the implementation file:</p><pre>// cpp/react-native-jsi-module.cpp<br><br>#include &quot;react-native-jsi-module.h&quot;<br><br>namespace jsimodule {<br><br>// Temporary C++ that we want to be imported from Rust.<br>double cpp_multiply(double a, double b)<br>{<br>  return a * b;<br>}<br> <br>void bridgeJSIFunctions(Runtime &amp;jsi) {<br> // Define `multiplyJSI` using JSI idioms.<br> auto multiplyJSI = Function::createFromHostFunction(<br>   jsi,<br>   PropNameID::forAscii(jsi, &quot;multiplyJSI&quot;),<br>   2, // number of arguments<br>   [](Runtime &amp;runtime, const Value &amp;thisValue, const Value *arguments, size_t count) -&gt; Value {<br>     if (count &lt; 2) {<br>       throw JSError(runtime, &quot;multiply() expects 2 arguments&quot;);<br>     }<br>     double a = arguments[0].asNumber();<br>     double b = arguments[1].asNumber();<br>     double ret = cpp_multiply(a, b);<br> <br>     return Value(ret);<br>     }<br>   );<br><br>   // Export `multiply` to React Native&#39;s global object<br>   jsi.global().setProperty(jsi, &quot;multiply&quot;, std::move(multiplyJSI));<br>}<br><br>} // namespace jsimodule</pre><p>We draw several observations:</p><ul><li>We have created the umbrella function, bridgeJSIFunctions(), which will be called on the app start and expose all its underlying lambda functions as properties on the RN global object. You usually create multiple JSI functions and setProperty() pairs through your projects; therefore, when this file gets unwieldy, you can extract each of these functions to other files.</li><li>multiply() now adheres to the JSI boilerplate and gives us access to the following parameters: <br>- runtime refers to the underlying JavaScript engine&#39;s runtime, usually Hermes or JavaScriptCore. You can learn more about switching between the two <a href="https://reactnative.dev/docs/hermes">here</a>. Any interaction with JSI has to go through this handle.<br>- thisValue represents the value of this within the scope of the JavaScript function call.<br>- arguments is an array of jsi::Value instances representing the arguments passed to the function.<br>- count is the number of arguments provided to the function.</li></ul><p>Everything seems settled, except we can&#39;t call this method directly from JS unless we alter the platform code.</p><h3>iOS</h3><p>Getting inside the ios folder, we&#39;ll first remove the template&#39;s Spec logic, as we will not be using <a href="https://github.com/reactwg/react-native-new-architecture#guides">codegen</a> for this project and will leave only the default Native Modules boilerplate:</p><pre>// ios/JsiModule.h<br><br>#ifdef __cplusplus<br>#import &quot;react-native-jsi-module.h&quot;<br>#endif<br><br>#import &lt;React/RCTBridgeModule.h&gt;<br>@interface JsiModule : NSObject &lt;RCTBridgeModule&gt;<br><br>@end</pre><p>Inside the implementation file, we aim to get a <strong>synchronous</strong> <strong>main-queue</strong> handle on JSI through React Native’s RCTBridge object - this will eventually install the JSI functions by calling the C++ bridgeJSIFunctions(). The thread meddling logic is because JSI is our module&#39;s foundational building block, and we don&#39;t want to allow any JavaScript execution until it is configured correctly from the start. Let&#39;s delete the old serialization code inside ios/JsiModule.mm and replace it with logic that calls bridgeJSIFunctions(). Optionally, we can create a bridgePlatformFunctions() that bridges iOS-specific logic as JSI functions. An example would be exposing the device name, which requires iOS platform code for retrieval and couldn&#39;t be done (or maybe not easily) with a shared C++ JSI function.</p><pre>// ios/JsiModule.mm<br><br>#import &quot;JsiModule.h&quot;<br>#import &quot;react-native-jsi-module.h&quot;<br><br>#import &lt;React/RCTBridge+Private.h&gt;<br>#import &lt;jsi/jsi.h&gt;<br><br>using namespace facebook::jsi;<br><br>@implementation JsiModule<br><br>RCT_EXPORT_MODULE()<br><br>// 👇 Add these methods:<br><br>// Convenient method to ensure JSI functions will be installed on the main thread.<br>+ (BOOL)requiresMainQueueSetup {<br>  return YES;<br>}<br><br>// Ensures no JavaScript will be executed until JSI is set up.<br>RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(bridgeJSIFunctions) {<br>  RCTBridge* bridge = [RCTBridge currentBridge];<br>  RCTCxxBridge* cxxBridge = (RCTCxxBridge*)bridge;<br>  Runtime *jsi = (Runtime *) cxxBridge.runtime;<br><br>  jsimodule::bridgeJSIFunctions(*jsi);<br><br>  // Optional: bridge iOS-platform specific logic<br>  bridgePlatformFunctions(*jsi);<br><br>  return @true;<br>}<br><br>// Optional:<br>static void bridgePlatformFunctions(Runtime &amp;jsi) {<br>  auto getDeviceName = Function::createFromHostFunction(jsi,<br>                                                        PropNameID::forAscii(jsi, &quot;getDeviceName&quot;),<br>                                                        0,<br>                                                        [](Runtime &amp;runtime,<br>                                                           const Value &amp;thisValue,<br>                                                           const Value *arguments,<br>                                                           size_t count) -&gt; Value {<br><br>    return String::createFromUtf8(runtime, [[[UIDevice currentDevice] name] UTF8String]);<br>  });<br><br>  jsi.global().setProperty(jsi, &quot;getDeviceName&quot;, std::move(getDeviceName));<br>}<br><br>@end</pre><h3>Android</h3><p><strong>Integrating JSI</strong></p><p>JSI doesn’t come bundled with the Android project as it was on iOS, so we need to drag it in. We will do so with CMakeLists.txt:</p><pre>// android/CMakeLists.txt<br><br>cmake_minimum_required(VERSION 3.4.1)<br>project(JsiModule)<br><br>set(CMAKE_VERBOSE_MAKEFILE ON)<br>set(CMAKE_CXX_STANDARD 14)<br><br>add_library(react-native-jsi-module SHARED<br>    ../cpp/react-native-jsi-module.cpp<br>    cpp-adapter.cpp<br>)<br><br># Specifies a path to native header files.<br>include_directories(<br>    ../cpp<br>)<br><br>// 👇 Add these lines:<br>find_package(ReactAndroid REQUIRED CONFIG)<br>target_link_libraries(<br>    react-native-jsi-module<br>    ReactAndroid::jsi<br>    android<br>)</pre><p>We continue accommodating the rest of the app to work with the new setup. Add these new lines to your android/build.gradle :</p><pre>// android/build.gradle<br><br>android {<br> // rest of block<br> <br>  // 👇 Enable Prefab for C++ library integration for JSI.<br>  buildFeatures {<br>    prefab true<br>  }<br>  <br>  defaultConfig {<br>    externalNativeBuild {<br>      cmake {<br>        cppFlags &quot;-O2 -frtti -fexceptions -Wall -fstack-protector-all&quot;<br>        // Solves: `User is using a static STL but library requires a <br>        // shared STL [//ReactAndroid/fabricjni]`:<br>        arguments &quot;-DANDROID_STL=c++_shared&quot; // 👈<br>      }<br>    }</pre><blockquote><em>💡</em> <strong><em>Optional</em></strong><em>: if running on the legacy architecture (</em><em>newArchEnabled=false), you will bump into an error similar to </em><em>Execution failed for task &#39;:app:mergeDebugNativeLibs’ […] 2 files found with path ‘lib//libjsi.so&#39;. To solve this, let’s enforce the packaging order of the shared object in </em><em>example/android/app/build.gradle:</em></blockquote><pre>// example/android/app/build.gradle<br><br>android {<br>    packagingOptions {<br>        pickFirst &#39;lib/x86/libjsi.so&#39;<br>        pickFirst &#39;lib/x86_64/libjsi.so&#39;<br>        pickFirst &#39;lib/armeabi-v7a/libjsi.so&#39;<br>        pickFirst &#39;lib/arm64-v8a/libjsi.so&#39;<br>    }<br>    // rest of block<br>}</pre><p><strong>Installing JSI</strong></p><p>Now that we’ve added JSI to the Android project, we’ll need to continue with platform steps just as we did with iOS. Unfortunately, Android doesn’t directly interface with C++, so we must add intermediate steps through <a href="https://en.wikipedia.org/wiki/Java_Native_Interface">JNI (Java Native Interface)</a>. The good part is that this scaffolding is already part of the boilerplate code — we’ll need to adjust it. Let’s remember how we did it for iOS, exporting the bridgeJSIFunctions() C++ function, but now for JNI:</p><pre>// android/cpp-adapter.cpp<br><br>#include &lt;jni.h&gt;<br>#include &lt;jsi/jsi.h&gt;<br>#include &quot;react-native-jsi-module.h&quot;<br><br>using namespace facebook::jsi;<br><br>// Optional:<br>void bridgePlatformFunctions(Runtime &amp;jsi);<br><br>extern &quot;C&quot; JNIEXPORT void JNICALL<br>Java_com_jsimodule_JsiModuleModule_jniBridgeJSIFunctions(JNIEnv *env, jobject thiz, jobject context,<br>                                                         jlong jsi_pointer)<br>{<br>    Runtime *jsi = reinterpret_cast&lt;Runtime *&gt;(jsi_pointer);<br>    if (jsi)<br>    {<br>        jsimodule::bridgeJSIFunctions(*jsi);<br><br>        // Optional: bridge platform-specific logic too.<br>        bridgePlatformFunctions(*jsi);<br>    }<br>}<br><br>// Optional:<br>void bridgePlatformFunctions(Runtime &amp;jsi)<br>{<br>    auto getDeviceName = Function::createFromHostFunction(jsi,<br>                                                          PropNameID::forAscii(jsi, &quot;getDeviceName&quot;),<br>                                                          0,<br>                                                          [](Runtime &amp;runtime,<br>                                                             const Value &amp;thisValue,<br>                                                             const Value *arguments,<br>                                                             size_t count) -&gt; Value<br>                                                          {<br>                                                              // JNI logic for another time!<br>                                                              return Value(runtime, String::createFromAscii(runtime, &quot;Not yet implemented.&quot;));<br>                                                          });<br><br>    jsi.global().setProperty(jsi, &quot;getDeviceName&quot;, std::move(getDeviceName));<br>}</pre><p>Let’s call this method from our Java implementation now:</p><pre>// android/src/main/com/jsimodule/JsiModuleModule.java<br><br>package com.jsimodule;<br><br>import androidx.annotation.NonNull;<br><br>import com.facebook.react.bridge.Promise;<br>import com.facebook.react.bridge.ReactApplicationContext;<br>import com.facebook.react.bridge.ReactContextBaseJavaModule;<br>import com.facebook.react.bridge.ReactMethod;<br>import com.facebook.react.module.annotations.ReactModule;<br><br>@ReactModule(name = JsiModuleModule.NAME)<br>public class JsiModuleModule extends ReactContextBaseJavaModule {<br>  public static final String NAME = &quot;JsiModule&quot;;<br><br> // 👇 Add this line:<br>  private native void jniBridgeJSIFunctions(ReactApplicationContext context, long jsiPtr);<br><br>  public JsiModuleModule(ReactApplicationContext reactContext) {<br>    super(reactContext);<br>  }<br><br>  @Override<br>  @NonNull<br>  public String getName() {<br>    return NAME;<br>  }<br><br>  // 👇 Same synchronous strategy as with iOS: making it synchronous.<br>  @ReactMethod(isBlockingSynchronousMethod = true)<br>  public boolean bridgeJSIFunctions() {<br>    try {<br>      System.loadLibrary(&quot;react-native-jsi-module&quot;);<br><br>      ReactApplicationContext context = getReactApplicationContext();<br>      jniBridgeJSIFunctions(<br>          context,<br>          context.getJavaScriptContextHolder().get());<br>      return true;<br>    } catch (Exception exception) {<br>      return false;<br>    }<br>  }<br>}</pre><p>One observation is that we don’t force the JSI installation to happen on the main (UI) thread as we did with iOS. Android provides flexibility with threading, and React Native’s architecture reduces the need for explicit main thread usage — however, we still want it to happen synchronously.</p><h3>JavaScript</h3><p>Now that we’ve set up the shared C++ base and JSI on platforms, we can finally call our multiply() method from JS. The first action point is to install the JSI bindings on the app start:</p><pre>// src/index.tsx<br><br>import { NativeModules, Platform } from &#39;react-native&#39;;<br><br>const LINKING_ERROR =<br>  `The package &#39;react-native-jsi-module&#39; doesn&#39;t seem to be linked. Make sure: \n\n` +<br>  Platform.select({ ios: &quot;- You have run &#39;pod install&#39;\n&quot;, default: &#39;&#39; }) +<br>  &#39;- You rebuilt the app after installing the package\n&#39; +<br>  &#39;- You are not using Expo Go\n&#39;;<br><br>const JsiModule =<br>  NativeModules.JsiModule ??<br>  new Proxy(<br>    {},<br>    {<br>      get() {<br>        throw new Error(LINKING_ERROR);<br>      },<br>    }<br>  );<br><br>const jsiCore = global as unknown as {<br>  multiply(a: number, b: number): number;<br>};<br><br>JsiModule.bridgeJSIFunctions();<br><br>export function multiply(a: number, b: number): number {<br>  return jsiCore.multiply(a, b);<br>}</pre><p>The last JSI integration step is modifying the app to switch from the asynchronous Promise:</p><pre>// example/src/App.tsx<br><br>// ... rest of page<br><br>React.useEffect(() =&gt; {<br>    setResult(multiply(3, 7));<br>  }, []);</pre><h3>Bridging Rust</h3><p>We’ll now create a small, multiply Rust library and show you how to integrate it with a JSI project.</p><h3>Create the Rust executable</h3><ul><li><strong>Rust project one-time setup</strong></li></ul><ol><li>Make sure to have Rust installed:<br>bash curl https://sh.rustup.rs -sSf | sh</li></ol><blockquote>You can choose the default installation or if you need to customize the minimal <em>profile</em> with the stable <em>toolchain</em>.</blockquote><p>2. Add support for cross-compilation to the mobile architectures. We will only target <strong>iOS devices</strong> and <strong>arm64 Android emulators</strong> for this example:</p><p>bash rustup target add aarch64-apple-ios aarch64-linux-android</p><p>3. Create your Rust project under the JSI project folder:</p><p>bash cargo new - lib rust_multiply_lib</p><p>4. Adjust the rust_multiply_lib/Cargo.toml so cargo build commands produce a C static library.</p><pre># rust_multiply_lib/Cargo.toml<br><br>[package]<br>name = &quot;rust_multiply_lib&quot;<br>version = &quot;0.1.0&quot;<br>edition = &quot;2021&quot;<br><br># 👇 Add this:<br>[lib]<br>crate-type = [<br>    &quot;staticlib&quot;, # Generates a C-compatible static library.<br>    # Optional: Also compile as a Rust library to enable Cargo features <br>    # like `tests/`, doc tests, and `examples/`<br>    &quot;lib&quot;,<br>]</pre><p>5. We must ensure the library generates all the required files for each possible architecture. We will configure this using rustflags in the .cargo/config.toml.</p><pre>cd rust_multiply_lib<br>mkdir -p .cargo<br>touch .cargo/config.toml</pre><pre># rust_multiply_lib/.cargo/config.toml<br><br># Convenience shorthands.<br>[alias]<br>build-ios = [&quot;build&quot;, &quot;--target&quot;, &quot;aarch64-apple-ios&quot;]<br>build-android = [&quot;build&quot;, &quot;--target&quot;, &quot;aarch64-linux-android&quot;]<br><br># Linker configuration settings.<br>[target.aarch64-apple-ios]<br>rustflags = [<br>  &quot;-C&quot;, &quot;link-arg=-isysroot&quot;, &quot;-C&quot;, &quot;link-arg=$(xcrun --sdk iphoneos --show-sdk-path)&quot;,<br>  &quot;-C&quot;, &quot;link-arg=-arch&quot;, &quot;-C&quot;, &quot;link-arg=arm64&quot;,<br>  &quot;-C&quot;, &quot;link-arg=-mios-version-min=10.0&quot;<br>]<br><br>[target.aarch64-linux-android]<br>linker = &quot;aarch64-linux-android21-clang&quot;<br>ar = &quot;aarch64-linux-android-ar&quot;</pre><ul><li><strong>Rust</strong> <strong>code</strong></li></ul><p>Let’s add a rust_multiply() function to rust_multiply_lib/src/lib.rs. The pub extern &quot;C&quot; directive allows us to export to C/FFI.</p><pre>// rust_multiply_lib/src/lib.rs<br><br>#[no_mangle] pub extern &quot;C&quot;<br>fn rust_multiply(a: f64, b: f64) -&gt; f64 {<br>    a * b<br>}</pre><ul><li><strong>Build and compilation</strong></li></ul><p>From the root of our Rust project, let’s compile the Rust code into the C static libraries: librust_multiply_lib.a:</p><pre>bash  cd rust_multiply_lib<br>cargo build-ios -release<br>cargo build-android -release</pre><blockquote><em>ℹ️ Use the </em><em>— release flag to create an optimized binary suitable for production under </em><em>rust_multiply_lib/target/release. For debugging purposes, omit this flag and the binary artifacts will be generated in the </em><em>rust_multiply_lib/target/debug directory, allowing for easier tracing and debugging.</em></blockquote><p>Assuming we target iOS simulators for this test, we will build and move them to our React Native project’s ios and android folders for convenient manipulation:</p><pre># iOS<br>cp \<br> rust_multiply_lib/target/aarch64-apple-ios/release/librust_multiply_lib.a \<br> react-native-jsi-module/ios/ <br><br># Android:<br>cp \<br> rust_multiply_lib/target/aarch64-linux-android/release/librust_multiply_lib.a \<br> react-native-jsi-module/android/</pre><h3><strong>Integration inside the JSI project</strong></h3><p>First, we need to ensure the project includes the binary file. We can do that through our Podspec and CMakeLists.txt.</p><p><strong>iOS</strong></p><pre><br># react-native-jsi-module.podspec<br><br># …rest of file<br> <br># 👇 Add this line:<br>s.vendored_libraries = &#39;ios/librust_multiply_lib.a&#39;</pre><p>Be sure to reinstall pods to propagate the changes with cd example/ios; RCT_NEW_ARCH_ENABLED=1 pod install.</p><p><strong>Android</strong></p><pre>// CMakeLists.txt<br><br>// 👇<br>add_library(rust_multiply STATIC IMPORTED)<br>set_target_properties(rust_multiply PROPERTIES IMPORTED_LOCATION &quot;${CMAKE_SOURCE_DIR}/librust_multiply_lib.a&quot;)<br><br>find_package(ReactAndroid REQUIRED CONFIG)<br>target_link_libraries(<br>    react-native-jsi-module<br>    ReactAndroid::jsi<br>    android<br>    rust_multiply // 👈<br>)</pre><p>For this particular example, temporarily remove the other architectures to make it build. Be sure to re-add them in production when you export all the required binaries:</p><pre>// example/gradle.properties<br><br>// 👇 Removed `armeabi-v7a`, `x86` and `x86_64`:<br>reactNativeArchitectures=arm64-v8a</pre><p><strong>C++</strong></p><p>Let’s now modify our JSI codebase to import the Rust code through the extern &quot;C&quot; declarations so that the C++ code knows their existence.</p><pre>#include &quot;react-native-jsi-module.h&quot;<br><br>// 👇 Declaration of the Rust function(s)<br>extern &quot;C&quot;<br>{<br>  // For instance, C++&#39;s `double` type is the equivalent of Rust&#39;s `f64`<br>  double rust_multiply(double a, double b); <br>}<br>// 👆<br>//<br>// 💡 If you don&#39;t know how the Rust signatures are translated to<br>// extern &quot;C&quot; declarations, you can use the `cbindgen` tool to<br>// generate these for you (to a separate file (which you could `#include` here)<br>// or to the stdout).<br><br>namespace jsimodule<br>{<br>  void bridgeJSIFunctions(Runtime &amp;jsi)<br>  {<br>    auto multiplyJSI = Function::createFromHostFunction(<br>        jsi,<br>        PropNameID::forAscii(jsi, &quot;multiplyJSI&quot;),<br>        2, // number of arguments<br>        [](Runtime &amp;runtime, const Value &amp;thisValue, const Value *arguments, size_t count) -&gt; Value<br>        {<br>          if (count &lt; 2)<br>          {<br>            throw JSError(runtime, &quot;multiply() expects 2 arguments&quot;);<br>          }<br><br>          double a = arguments[0].asNumber();<br>          double b = arguments[1].asNumber();<br><br>          double ret = rust_multiply(a, b); // 👈<br><br>          return Value(ret);<br>        });<br><br>    jsi.global().setProperty(jsi, &quot;multiply&quot;, std::move(multiplyJSI));<br>  }<br><br>} // namespace jsimodule</pre><p>Be sure to run the app on the corresponding architectures and modes — for this example, <strong>iOS devices</strong> and <strong>Android arm64 emulators</strong>.</p><h3>Next steps</h3><p>As time passed, we integrated multiple Ditto improvements that were worth considering. Here’s a list of challenges that were solved or are works in progress and that can be explained in future posts:</p><ul><li>Targeting all architectures for iOS (using a lipo-ed .xcframework).</li><li>Integrating dynamic libraries for Android (.so&#39;s).</li><li>Generating and including C header files for the Rust lib.</li><li>Bridging Rust processes that need to run on background threads.</li><li>Memory management over FFI. Implementing advanced JS constructs like WeakRef and FinalizationRegistry.</li><li>Hooking into the JavaScript SDK’s source files, unit tests, and CI automation.</li><li>Moving as much platform code possible to JSI.</li><li>Switching from a Legacy Module to a TurboModule.</li></ul><h3>Link to repo</h3><p><a href="https://github.com/teodorciuraru/rn-jsi-rust-bridging">GitHub - getditto/rn-jsi-rust-bridging: Sample app for the Bridging React Native and Rust via JSI blog post.</a></p><h3>Original blog post</h3><p><a href="https://ditto.live/blog/bridging-react-native-and-rust-via-jsi">https://ditto.live/blog/bridging-react-native-and-rust-via-jsi</a></p><h3>Resources</h3><ul><li><a href="https://blog.notesnook.com/getting-started-react-native-jsi">https://blog.notesnook.com/getting-started-react-native-jsi</a></li><li><a href="https://mozilla.github.io/firefox-browser-architecture/experiments/2017-09-06-rust-on-ios.html">https://mozilla.github.io/firefox-browser-architecture/experiments/2017-09-06-rust-on-ios.html</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=458df647f8fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>