Skip to content

鸿蒙 NEXT 开发:通过 N-API 调用 Rust

https://blog.csdn.net/zrufo747/article/details/132309037

创建模板工程

  1. 使用 File->New->Create Project 创建 Native C++ 模板工程。
  2. 删除 entry/src/main/cpp
  3. 编辑 entry/build-profile.json5,删除 externalNativeOptions

创建 rust 项目

我们使用 ohos-rs 框架简化开发。

sh
ohrs init xx

官方文档:https://ohos-rs.github.io/docs/basic/quick-start.html

编写一个基础的 add() 方法:

rs
use napi_derive_ohos::napi;

#[napi]
pub fn add(a: u32,b: u32) -> u32 {
    a + b
}

构建 so 文件

sh
ohrs build

会生成如下文件:

dist/arm64-v8a/libhello.so
dist/armeabi-v7a/libhello.so
dist/x86_64/libhello.so
dist/index.d.ts
  1. 拷贝 dist/index.d.tsentry/src/main/rust/types/libhello/index.d.ts
  2. 创建 entry/src/main/rust/types/libhello/oh-package.json5
    json
    {
      "name": "libhello.so",
      "types": "./index.d.ts",
      "version": "",
      "description": "Please describe the basic information."
    }
  3. 修改 entry/oh-package.json5 dependencies
    json
    {
      "name": "entry",
      "version": "1.0.0",
      "description": "Please describe the basic information.",
      "main": "",
      "author": "",
      "license": "",
      "dependencies": {
        "libhello.so": "file:./src/main/rust/types/libhello"
      }
    }
  4. 拷贝 dist/arm64-v8a/libhello.soentry/libs/arm64-v8a/libhello.so

TIP

entry/src/main/rust/types/libhello/oh-package.json5libhellodist/arm64-v8a/libhello.soso 的名字需要一致。

测试

修改测试页 Index.ets

ts
import testNapi from "libhello.so";

// onClick 里添加
hilog.info(0x0000, "testTag", "Test NAPI 2 + 3 = %{public}d", testNapi.add(2, 3));

最后编辑时间:

Version 4.2 (core-1.3.4)