#打卡不停更#Native C++应用Demo示例(eTS) 原创

Soon_L
发布于 2022-10-9 22:36
浏览
2收藏

本文主要分享在软通动力扬帆系列“竞”OpenHarmony开发板上测试Native C++ 应用开发,实现eTS调用Native C++ 程序实现对给定的两个数进行加减乘除运算示例(eTS)

1.新建OpenHarmony Native C++工程

选择File->New->Create Project -> OpenHarmony -> Native C++点击Next
 #打卡不停更#Native C++应用Demo示例(eTS)-鸿蒙开发者社区
输入Project name,选择SDK版本9
 #打卡不停更#Native C++应用Demo示例(eTS)-鸿蒙开发者社区
点击Finish,如果Native SDK 没有下载则会出现以下界面,点击Configure Now
 #打卡不停更#Native C++应用Demo示例(eTS)-鸿蒙开发者社区

下载Native SDK
 #打卡不停更#Native C++应用Demo示例(eTS)-鸿蒙开发者社区
Native SDK下载完成后点击Finish 进入工程
 #打卡不停更#Native C++应用Demo示例(eTS)-鸿蒙开发者社区

2.源码修改

2.1 工程主要文件说明

工程初始化后目录结构如下图,主要文件为红色框内文件
 #打卡不停更#Native C++应用Demo示例(eTS)-鸿蒙开发者社区
主要文件文件说明如下:

├── cpp:C++代码区									
│   ├── types:                                          // 接口存放文件夹
│   │   └── libentry							
│   │       ├── index.d.ts                              // 接口文件
│   │       └── package.json                            // 接口注册配置文件
│   ├── CmakeList.txt                                   // Cmake打包配置文件
│   └── hello.cpp                                       // C++源代码
└── ets                                                 // ets代码区
    └── Application
    │   └── AbilityStage.ts                             // Hap包运行时类
    ├── MainAbility
    │   └── MainAbility.ts                              // Ability,提供对Ability生命周期、上下文环境等调用管理
    └── pages
        └── index.ets                                   // 主页面

2.2 cpp源码编写

自带的案例已经实现了加法运算的接口,本案例在此基础上加入减法乘法除法,entry\src\main\cpp\hello.cpp主要修改如下

参考“Add”方法,实现Sub、Mul、Div

static napi_value Sub(napi_env env, napi_callback_info info)
{
    size_t requireArgc = 2;
    size_t argc = 2;
    napi_value args[2] = {nullptr};

    napi_get_cb_info(env, info, &argc, args , nullptr, nullptr);

    napi_valuetype valuetype0;
    napi_typeof(env, args[0], &valuetype0);

    napi_valuetype valuetype1;
    napi_typeof(env, args[1], &valuetype1);

    double value0;
    napi_get_value_double(env, args[0], &value0);

    double value1;
    napi_get_value_double(env, args[1], &value1);

    napi_value sum;
    napi_create_double(env, value0 - value1, &sum);

    return sum;

}
static napi_value Mul(napi_env env, napi_callback_info info)
{
    size_t requireArgc = 2;
    size_t argc = 2;
    napi_value args[2] = {nullptr};

    napi_get_cb_info(env, info, &argc, args , nullptr, nullptr);

    napi_valuetype valuetype0;
    napi_typeof(env, args[0], &valuetype0);

    napi_valuetype valuetype1;
    napi_typeof(env, args[1], &valuetype1);

    double value0;
    napi_get_value_double(env, args[0], &value0);

    double value1;
    napi_get_value_double(env, args[1], &value1);

    napi_value sum;
    napi_create_double(env, value0*value1, &sum);

    return sum;

}
static napi_value Div(napi_env env, napi_callback_info info)
{
    size_t requireArgc = 2;
    size_t argc = 2;
    napi_value args[2] = {nullptr};

    napi_get_cb_info(env, info, &argc, args , nullptr, nullptr);

    napi_valuetype valuetype0;
    napi_typeof(env, args[0], &valuetype0);

    napi_valuetype valuetype1;
    napi_typeof(env, args[1], &valuetype1);

    double value0;
    napi_get_value_double(env, args[0], &value0);

    double value1;
    napi_get_value_double(env, args[1], &value1);

    napi_value sum;
    napi_create_double(env, value0/value1, &sum);

    return sum;

}

Init中注册对外接口名为“sub”、“mul”、“div”

EXTERN_C_START
static napi_value Init(napi_env env, napi_value exports)
{
    napi_property_descriptor desc[] = {
        { "add", nullptr, Add, nullptr, nullptr, nullptr, napi_default, nullptr },
        { "sub", nullptr, Sub , nullptr, nullptr, nullptr, napi_default, nullptr },
        { "mul", nullptr, Mul , nullptr, nullptr, nullptr, napi_default, nullptr },
        { "div", nullptr, Div , nullptr, nullptr, nullptr, napi_default, nullptr },
    };
    napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);
    return exports;
}
EXTERN_C_END

2.3 index.d.ts接口文档编写

src/main/cpp/types/libentry/index.d.ts
添加以下接口

export const sub: (a: number, b: number) => number;
export const mul: (a: number, b: number) => number;
export const div: (a: number, b: number) => number;

2.4 界面实现

src/main/ets/pages/index.ets
中通过import testNapi from 'libentry.so’引入SO包,当点击按钮时调用对应的方法

import testNapi from 'libentry.so'

@Entry
@Component
struct Index {
  private textInputController1: TextInputController = new TextInputController()
  private textInputController2: TextInputController = new TextInputController()
  private tittle: string = '调用C标准库示例'
  private message: string = '对给定的两个数进行加减乘除运算'
  private tipsNum1: string = '请输入第一个数:'
  private tipsNum2: string = '请输入第二个数:'
  private tipsResult: string = '结果:'
  private buttonAdd: string = '加'
  private buttonSub: string = '减'
  private buttonMul: string = '乘'
  private buttonDiv: string = '除'
  @State result: number = 0
  @State num1: number = 0.0
  @State num2: number = 0.0

  build() {
    Row() {
      Column() {
        Row(){
          Text(this.tittle).height('100%').align(Alignment.Center).fontSize(40).fontWeight(800)
        }.height('10%').width('100%').justifyContent(FlexAlign.Center)
        Row(){
          Text(this.message).height('100%').align(Alignment.Center).fontSize(24).fontWeight(500)
        }.height('15%').width('100%').justifyContent(FlexAlign.Center)
        Row(){
          Text(this.tipsNum1).fontColor(Color.Black).fontSize(24).width('30%').height('100%').margin({left:30})
          TextInput({ placeholder: '请输入第一个数字:', controller:this.textInputController1}).type(InputType.Number)
            .height('100%').width('60%').margin({left:10,right:30})
            .onChange(value =>{this.num1 = parseFloat(value)})
        }.height('5%').width('100%').justifyContent(FlexAlign.Start)
        Row(){
          Text(this.tipsNum2).fontColor(Color.Black).fontSize(24).width('30%').height('100%').margin({left:30})
          TextInput({ placeholder: '请输入第二个数字:', controller:this.textInputController2}).type(InputType.Number)
            .height('100%').width('60%').margin({left:10,right:30})
            .onChange(value =>{this.num2 = parseFloat(value)})
        }.height('5%').width('100%').margin({top:20})
        Row(){
          Text(this.tipsResult).fontColor(Color.Black).fontSize(24).width('40%').height('100%').margin({left:30})
          Text(''+this.result).fontColor(Color.Black).fontSize(30).width(60).height(200).width('60%').height('100%')
        }.height('10%').width('100%').touchable(false)
        Row(){
          Button(this.buttonAdd)
            .fontSize(40)
            .fontWeight(FontWeight.Bold)
            .margin({top:5})
            .height(100)
            .width(100)
            .onClick(() => {
              this.result = testNapi.add(this.num1,this.num2)
            })
          Button(this.buttonSub)
            .fontSize(40)
            .fontWeight(FontWeight.Bold)
            .margin({top:5})
            .height(100)
            .width(100)
            .onClick(() => {
              this.result = testNapi.sub(this.num1,this.num2)
            })
          Button(this.buttonMul)
            .fontSize(40)
            .fontWeight(FontWeight.Bold)
            .margin({top:5})
            .height(100)
            .width(100)
            .onClick(() => {
              this.result = testNapi.mul(this.num1,this.num2)
            })
          Button(this.buttonDiv)
            .fontSize(40)
            .fontWeight(FontWeight.Bold)
            .margin({top:5})
            .height(100)
            .width(100)
            .onClick(() => {
              this.result = testNapi.div(this.num1,this.num2)
            })
        }.height('30%').width('100%').justifyContent(FlexAlign.Center)
      }
      .width('100%')
    }
    .height('100%')
  }
}

3 运行效果演示

加法
 #打卡不停更#Native C++应用Demo示例(eTS)-鸿蒙开发者社区
减法
 #打卡不停更#Native C++应用Demo示例(eTS)-鸿蒙开发者社区
乘法
 #打卡不停更#Native C++应用Demo示例(eTS)-鸿蒙开发者社区
除法
 #打卡不停更#Native C++应用Demo示例(eTS)-鸿蒙开发者社区

©著作权归作者所有,如需转载,请注明出处,否则将追究法律责任
已于2022-10-10 10:18:08修改
8
收藏 2
回复
举报
4条回复
按时间正序
/
按时间倒序
红叶亦知秋
红叶亦知秋

Native调用讲解的很详细

回复
2022-10-10 10:17:47
Haoc_小源同学
Haoc_小源同学

学到了

回复
2022-10-10 10:55:34
物联风景
物联风景

不错不错,跟着廖总学东西

1
回复
2022-10-10 14:18:40
wx6572d6ddd35c0
wx6572d6ddd35c0

如何异步调用

回复
2023-12-12 14:27:20
回复
    相关推荐