In this lesson, you will learn how to bypass the traditional "bridge" bottleneck by integrating C++ libraries directly into the JavaScript runtime using JSI or N-API.
Beyond the Bridge
In earlier chapters, we discussed the Native Module system, where JavaScript communicates with native code by serializing data into JSON strings across a "bridge." This is asynchronous and can be slow for high-performance tasks. By integrating C++ directly, we remove this middleman, allowing JavaScript to call C++ functions as if they were local functions, with near-zero overhead.
The Power of JSI
The JavaScript Interface (JSI) is a set of C++ APIs that allows the JavaScript engine (like Hermes) to hold references to C++ objects. Instead of copying data back and forth, both the JavaScript side and the C++ side can share memory directly.
For example, imagine you have a heavy C++ image-processing library. Instead of passing image buffers through the serialized bridge, you can expose a JSI function that lets JavaScript trigger C++ logic on that memory buffer directly:
// A simplified conceptual look at exposing a C++ function to JS
jsi::Function processImage = jsi::Function::createFromHostFunction(
runtime,
name,
1,
[](jsi::Runtime& runtime, ...) {
// Direct C++ logic execution happens here!
return jsi::Value(true);
}
);
Why use N-API or JSI?
- N-API: Often used for Node.js-style environments, it provides an abstraction layer that ensures your C++ code remains stable even if the underlying JavaScript engine changes.
- JSI: The modern standard for React Native. It allows for synchronous communication, which is a massive performance upgrade for things like encryption, audio processing, or game physics engines that require real-time updates.
By utilizing these tools, you aren't just sending "messages" to native code; you are extending the capabilities of the JavaScript runtime itself, allowing your app to handle computationally expensive tasks at native speeds while remaining cross-platform.
Key Takeaway: Bridging C++ via JSI or N-API allows JavaScript to execute high-performance logic in the same memory space as native code, eliminating bridge serialization latency.