You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何借助React Native JSI在安卓和iOS应用中集成C++算法代码?

React Native 借助JSI集成C++代码实现跨平台算法

当然可以通过React Native JSI实现C算法的跨平台集成。JSI(JavaScript Interface)是React Native提供的底层接口,允许JavaScript直接与C代码通信,无需经过传统的JS桥接层,性能优势明显,特别适合计算密集型的算法场景,同时完美支持安卓和iOS双平台。

以下是详细的分步集成流程:

一、基础环境准备

  • 确保已配置好React Native开发环境(Node.js、Android Studio/Xcode、NDK(安卓需要))
  • 创建或打开目标RN项目:npx react-native init JsiCppDemo(已有项目可跳过此步)

二、编写C++核心算法代码

在项目根目录新建cpp文件夹,存放算法实现文件,以下是简单乘法示例:

cpp/MathAlgorithms.h

#pragma once
#include <jsi/jsi.h>

using namespace facebook;

// 声明JSI绑定安装函数
void installMathAlgorithms(jsi::Runtime &runtime);

cpp/MathAlgorithms.cpp

#include "MathAlgorithms.h"

// 实现C++算法:两数相乘
jsi::Value multiply(jsi::Runtime &runtime, const jsi::Value &thisValue, const jsi::Value *arguments, size_t count) {
    if (count != 2 || !arguments[0].isNumber() || !arguments[1].isNumber()) {
        throw jsi::JSError(runtime, "参数错误:需要传入两个数字");
    }
    return jsi::Value(arguments[0].asNumber() * arguments[1].asNumber());
}

// 将C++函数绑定到JS全局对象
void installMathAlgorithms(jsi::Runtime &runtime) {
    auto multiplyFunc = jsi::Function::createFromHostFunction(
        runtime,
        jsi::PropNameID::forAscii(runtime, "multiply"),
        2,
        multiply
    );
    runtime.global().setProperty(runtime, "multiply", std::move(multiplyFunc));
}

三、iOS端集成配置

  1. 打开iOS项目:在Xcode中打开ios/JsiCppDemo.xcworkspace
  2. 导入C++文件:右键项目根节点 → Add Files to "JsiCppDemo",选择根目录的cpp文件夹,勾选「Create groups」和对应目标项目,点击Add
  3. 配置编译参数:
    • 进入项目Build Settings,找到Header Search Paths,添加$(SRCROOT)/../cpp和$(NODE_MODULES_DIR)/react-native/ReactCommon/jsi,均设置为recursive
    • 找到C++ Standard,设置为C++17或更高版本
  4. 修改AppDelegate为Objective-C++:
    • 若原有AppDelegate是.m后缀,重命名为.mm(否则无法编译C++代码)
    • 修改AppDelegate.mm,在启动时安装JSI绑定:
      #import <React/RCTBridgeDelegate.h>
      #import <UIKit/UIKit.h>
      #include "MathAlgorithms.h"
      #import <ReactCommon/RCTTurboModuleManager.h>
      
      @interface AppDelegate : UIResponder <UIApplicationDelegate, RCTBridgeDelegate>
      
      @property (nonatomic, strong) UIWindow *window;
      
      @end
      
      @implementation AppDelegate
      
      - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
      {
        // 保留原有初始化代码
        RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions];
        RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge
                                                         moduleName:@"JsiCppDemo"
                                                  initialProperties:nil];
      
        // 安装JSI绑定
        RCTTurboModuleManager *turboModuleManager = bridge.turboModuleManager;
        if (turboModuleManager != nil) {
            facebook::jsi::Runtime &runtime = turboModuleManager->jsRuntime();
            installMathAlgorithms(runtime);
        }
      
        // 保留原有窗口设置代码
        self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
        UIViewController *rootViewController = [UIViewController new];
        rootViewController.view = rootView;
        self.window.rootViewController = rootViewController;
        [self.window makeKeyAndVisible];
        return YES;
      }
      
      // 保留原有其他方法(如sourceURLForBridge等)
      @end
      
  5. 运行iOS项目:执行npx react-native run-ios

四、安卓端集成配置

  1. 配置Gradle支持C++:
    • 修改android/build.gradle,添加C++版本配置:
      buildscript {
          // 保留原有代码
      }
      
      allprojects {
          repositories {
              // 保留原有代码
          }
      }
      
      ext {
          cppVersion = "c++17"
      }
      
    • 修改android/app/build.gradle,启用CMake并配置NDK:
      android {
          // 保留原有代码
          defaultConfig {
              // 保留原有代码
              externalNativeBuild {
                  cmake {
                      cppFlags "-std=c++17"
                      arguments "-DANDROID_STL=c++_shared"
                  }
              }
          }
      
          externalNativeBuild {
              cmake {
                  path file("src/main/cpp/CMakeLists.txt")
              }
          }
      }
      
  2. 创建CMake配置文件:
    在android/app/src/main下新建cpp文件夹,创建CMakeLists.txt:
    cmake_minimum_required(VERSION 3.18.1)
    
    project("jsi-cpp-algorithms")
    
    // 引入头文件路径
    include_directories(
        ../../../../cpp
        ${REACT_NATIVE_DIR}/ReactCommon/jsi
        ${REACT_NATIVE_DIR}/ReactCommon
        ${REACT_NATIVE_DIR}/ReactAndroid/src/main/jni
        ${REACT_NATIVE_DIR}/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/jni
    )
    
    // 添加C++源文件
    add_library(
        jsi-cpp-algorithms
        SHARED
        ../../../../cpp/MathAlgorithms.cpp
        native-lib.cpp
    )
    
    // 链接依赖库
    find_package(fbjni REQUIRED CONFIG)
    find_package(ReactAndroid REQUIRED CONFIG)
    
    target_link_libraries(
        jsi-cpp-algorithms
        ReactAndroid::jsi
        ReactAndroid::reactnative
        fbjni::fbjni
        log
    )
    
  3. 编写JNI初始化代码:
    在android/app/src/main/cpp下创建native-lib.cpp:
    #include <jni.h>
    #include <fbjni/fbjni.h>
    #include <react/jni/JSIOnLoad.h>
    #include "MathAlgorithms.h"
    
    using namespace facebook;
    
    extern "C" JNIEXPORT void JNICALL
    Java_com_jsicppdemo_MainApplication_installJsi(
        JNIEnv* env,
        jobject thiz,
        jlong jsiRuntimePtr) {
        auto runtime = reinterpret_cast<jsi::Runtime*>(jsiRuntimePtr);
        if (runtime != nullptr) {
            installMathAlgorithms(*runtime);
        }
    }
    

    注意:Java_com_jsicppdemo_MainApplication_installJsi中的包名com_jsicppdemo要与你的项目包名一致(比如项目名为JsiCppDemo,包名通常是com.jsicppdemo)

  4. 修改MainApplication.java:
    package com.jsicppdemo;
    
    import android.app.Application;
    import com.facebook.react.PackageList;
    import com.facebook.react.ReactApplication;
    import com.facebook.react.ReactNativeHost;
    import com.facebook.react.ReactPackage;
    import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint;
    import com.facebook.react.defaults.DefaultReactNativeHost;
    import com.facebook.soloader.SoLoader;
    import java.util.List;
    
    public class MainApplication extends Application implements ReactApplication {
    
      private final ReactNativeHost mReactNativeHost =
          new DefaultReactNativeHost(this) {
            @Override
            public boolean getUseDeveloperSupport() {
              return BuildConfig.DEBUG;
            }
    
            @Override
            protected List<ReactPackage> getPackages() {
              List<ReactPackage> packages = new PackageList(this).getPackages();
              return packages;
            }
    
            @Override
            protected String getJSMainModuleName() {
              return "index";
            }
    
            @Override
            protected boolean isNewArchEnabled() {
              return BuildConfig.IS_NEW_ARCHITECTURE_ENABLED;
            }
    
            @Override
            protected Boolean isHermesEnabled() {
              return BuildConfig.IS_HERMES_ENABLED;
            }
          };
    
      @Override
      public ReactNativeHost getReactNativeHost() {
        return mReactNativeHost;
      }
    
      @Override
      public void onCreate() {
        super.onCreate();
        SoLoader.init(this, /* native exopackage */ false);
        if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) {
          DefaultNewArchitectureEntryPoint.load();
          // 调用JNI方法安装JSI绑定
          installJsi();
        }
      }
    
      // 声明JNI方法
      private native void installJsi();
    
      // 加载C++库
      static {
          System.loadLibrary("jsi-cpp-algorithms");
      }
    }
    
  5. 运行安卓项目:执行npx react-native run-android

五、在JavaScript中调用C++算法

修改App.js,直接调用全局的multiply函数(已通过JSI绑定到JS):

import React from 'react';
import { View, Text, Button, Alert } from 'react-native';

const App = () => {
  const calculate = () => {
    const result = multiply(8, 9);
    Alert.alert('计算结果', `8 × 9 = ${result}`);
  };

  return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
      <Text style={{ fontSize: 18, marginBottom: 20 }}>调用C++实现的乘法算法</Text>
      <Button title="计算8×9" onPress={calculate} />
    </View>
  );
};

export default App;

关键注意事项

  • React Native版本需≥0.60,JSI从该版本开始内置
  • iOS端必须使用.mm后缀的文件来支持Objective-C++混合编译
  • 安卓端需确保NDK版本与React Native要求匹配(可参考RN官方文档)
  • 处理JSI类型转换时要严谨,避免因类型不匹配导致崩溃
  • 复杂算法建议将C++代码编译为静态库后再集成,便于维护

内容的提问来源于stack exchange,提问作者Venda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 03:40:33