概要
本実装例ではDevEco Studioを用いたNative C++アプリケーション開発手法を解説する。NAPI経由でC標準数学ライブラリのhypot関数を呼び出し、二値の平方和平方根を計算するサンプルを実装する。UI入力値を受け取り、計算結果を表示するインタラクティブな処理フローを構築する。
関連技術
- NAPI: Node.js互換インターフェースのHarmonyOS実装
- 標準ライブラリ対応: C/C++標準ライブラリ、OpenSL ES、zlibのネイティブサポート
環境構築
ソフトウェア要件
- DevEco Studio 3.1 Release
- OpenHarmony SDK API version 9
ハードウェア要件
- 開発ボード: RK3568
- OpenHarmony 3.2 Release
セットアップ手順
- OpenHarmonyバイナリ(3.2 Release)を取得
- DevEco Device Toolをインストール
- RK3568開発ボードのファームウェアを更新
- DevEco Studioで"Empty Ability"テンプレートを使用した新規プロジェクト作成
- 実機デバッグ環境を設定
プロジェクト構成
entry/src/main
├──cpp
│ ├──CMakeLists.txt
│ ├──math_ops.cpp
│ └──types
│ └──libmath
│ ├──index.d.ts
│ └──oh-package.json5
├──ets
│ ├──entryability
│ │ └──EntryAbility.ts
│ └──pages
│ └──MainPage.ets
└──resources
技術構成
アプリケーション層
- C++層: ネイティブ演算ロジック実装
- ArkTS層: UI制御とネイティブ呼び出し
- ビルドツールチェーン: CMakeによる動的ライブラリ生成
ビルドプロセス
ArkTSとC++間の相互運用はNAPIを介して実現され、CMakeが生成する共有オブジェクト(.so)をArkTSが直接インポート可能な構造を採用する。
ネイティブ実装詳細
モジュール登録
static napi_module mathModule = {
nm_version = 1,
nm_register_func = Initialize,
nm_modname = "math_ops"
};
extern "C" __attribute__((constructor)) void RegisterMathModule() {
napi_module_register(&mathModule);
}
メソッド公開
static napi_value Initialize(napi_env env, napi_value exports) {
napi_property_descriptor methods[] = {
{ "computeHypotenuse", nullptr, CalculateHypotenuse, nullptr, nullptr, nullptr, napi_default, nullptr }
};
napi_define_properties(env, exports, sizeof(methods)/sizeof(methods[0]), methods);
return exports;
}
数学演算実装
#include <cmath>
static napi_value CalculateHypotenuse(napi_env env, napi_callback_info info) {
constexpr int ARG_COUNT = 2;
napi_value args[ARG_COUNT];
size_t arg_count = ARG_COUNT;
napi_get_cb_info(env, info, &arg_count, args, nullptr, nullptr);
double val1, val2;
napi_get_value_double(env, args[0], &val1);
napi_get_value_double(env, args[1], &val2);
double hypotenuse = std::hypot(val1, val2);
napi_value result;
napi_create_double(env, hypotenuse, &result);
return result;
}
型定義
// index.d.ts
export const computeHypotenuse: (x: number, y: number) => number;
ビルド設定
cmake_minimum_required(VERSION 3.4.1)
project(MathOperations)
add_library(math_ops SHARED math_ops.cpp)
target_link_libraries(math_ops PUBLIC
hilog_ndk.z
libace_napi.z.so
libc++.a)
ArkTS連携
import mathOps from 'libmath_ops.so';
@Entry
@Component
struct MathCalculator {
@State result: string = '0.00'
build() {
Column() {
// UI components
Button('計算実行')
.onClick(() => {
const hypotenuse = mathOps.computeHypotenuse(xValue, yValue);
this.result = hypotenuse > 1e6 ?
hypotenuse.toExponential(4) :
hypotenuse.toFixed(4);
})
}
}
}
UI設計
@Entry
@Component
struct MathCalculator {
@State xInput: string = ''
@State yInput: string = ''
build() {
Column() {
TextInput({ text: this.xInput })
.type(InputType.Number)
.onChange(val => this.xInput = val)
TextInput({ text: this.yInput })
.type(InputType.Number)
.onChange(val => this.yInput = val)
Text(`結果: ${this.result}`)
Button('計算実行')
}
}
}