はじめに
前回の記事「NAPIによるサードパーティライブラリ移植(1)—Hello OpenHarmony NAPI」ではROMパッケージ型のNAPIプロジェクトを構築し、C++のダイナミックライブラリをシステムROMに組み込む方法を紹介しました。今回は同じ機能を備えたhellonapi.cppとindex.etsを用いて、IDE(DevEco Studio)を使ってRAMパッケージ方式のNAPIプロジェクトを構築する方法を解説します。
開発環境
- IDE: DevEco Studio 3.0 Release
- 対象デバイス: DAYU200開発ボード
プロジェクト作成
DevEco Studioを起動し、「Native C++」プロジェクトを作成します。
- SDK: API9
- Model: Stageモデルを選択
ソースコード実装
C++実装ファイル
自動生成されたhello.cppをhellonapi.cppにリネームし、以下のように実装します:
#include "napi/native_api.h"
#include <string>
// NAPIメソッド実装
static napi_value GetGreetingMessage(napi_env env, napi_callback_info info) {
napi_value result;
std::string message = "OpenHarmony NAPIによるメッセージ";
napi_create_string_utf8(env, message.c_str(), message.length(), &result);
return result;
}
// プロパティ定義
static napi_value ModuleInitialize(napi_env env, napi_value exports) {
static napi_property_descriptor properties[] = {
{ "showGreeting", nullptr, GetGreetingMessage, nullptr, nullptr, nullptr, napi_default, nullptr }
};
napi_define_properties(env, exports, sizeof(properties) / sizeof(properties[0]), properties);
return exports;
}
// モジュール定義
static napi_module greetingModule = {
.nm_version = 1,
.nm_flags = 0,
.nm_filename = nullptr,
.nm_register_func = ModuleInitialize,
.nm_modname = "greeting",
.nm_priv = ((void*)0),
.reserved = { 0 },
};
// コンストラクタ
extern "C" __attribute__((constructor)) void RegisterGreetingModule() {
napi_module_register(&greetingModule);
}
CMakeLists.txt設定
以下の内容でCMakeビルド設定を行います:
cmake_minimum_required(VERSION 3.4.1)
project(GreetingModule)
set(SDK_ROOT /opt/sdk/native/3.2.7.5/sysroot/usr)
include_directories(${SDK_ROOT}/include)
add_library(greeting SHARED hellonapi.cpp)
target_link_libraries(greeting PUBLIC libace_napi.z.so)
TypeScript宣言ファイル
index.d.tsの内容:
export const showGreeting: () => string;
UI実装
index.etsの内容:
import prompt from '@system.prompt'
import greeting from 'libgreeting.so'
@Entry
@Component
export struct GreetingUI {
build() {
Column({ space: 10 }) {
Button("NAPI: greeting.showGreeting()")
.fontSize(24)
.onClick(() => {
let message = greeting.showGreeting()
prompt.showToast({ message: message })
})
}
.width('100%')
.height('100%')
}
}
パッケージ設定
package.json:
{
"name": "libgreeting.so",
"types": "./index.d.ts"
}
entry/package.json:
"dependencies": {
"libgreeting.so": "file:src/main/cpp"
}
HAPパッケージの実行結果
ROMパッケージ方式と同様の動作を確認できます。
RAMパッケージとROMパッケージの比較
- RAM方式では
libgreeting.so、ROM方式ではlibgreeting.z.soが使用される - RAM方式はCMakeによる設定のみで完了するが、ROM方式はGNビルド設定(
BUILD.gn、ohos.buildなど)が必要 - RAM方式の.d.tsファイルではアロー関数表記
=>が必要 - RAM方式のバイナリ出力パス:
entry/build/default/intermediates/libs/default/arm64-v8a entry/build/default/intermediates/cmake/default/obj/arm64-v8a