鸿蒙next开发:ArkTS语言-静态方式加载native模块

往期鸿蒙全套实战文章必看:(附带鸿蒙全栈学习资料)


静态方式加载native模块

在ES6(ECMAScript6.0)模块设计中,社区使用import语法加载其他文件导出的内容(ECMA规范定义语法规格)。

为支持开发者使用该功能导入native模块(so)导出的内容,ArkTS进行了相关适配,并提供了以下几种支持写法。

直接导入

在native模块的index.d.ts文件中导出,在文件内直接导入。

具名导入

// libentry.so对应的index.d.ts
export const add: (a: number, b: number) => number;
// test.ets
import { add } from 'libentry.so'
add(2, 3);

默认导入

// libentry.so对应的index.d.ts
export const add: (a: number, b: number) => number;
// test.ets
import entry from 'libentry.so'
entry.add(2, 3);

命名空间导入

// libentry.so对应的index.d.ts
export const add: (a: number, b: number) => number;
// test.ets
import * as add from 'libentry.so'
add.add(2, 3);

间接导入

转为具名变量导出再导入

// test1.ets
import hilog from '@ohos.hilog'
export { hilog }
// test2.ets
import { hilog } from './test1'
hilog.info(0x000, 'testTag', '%{public}s', 'test');

转为命名空间导出再导入

// libentry.so对应的index.d.ts
export const add: (a: number, b: number) => number;
// test1.ets
export * from 'libentry.so'
// test2.ets
import { add } from './test1'
add(2, 3);

注意

不支持native模块导出和导入同时使用命名空间。

反例:

// test1.ets
export * from 'libentry.so'
// test2.ets
import * as add from 'file1'
// 无法获取add对象

动态导入

直接导入

// libentry.so对应的index.d.ts
export const add: (a: number, b: number) => number;
// test.ets
import('libentry.so').then((ns:ESObject) => {
    ns.default.add(2, 3);
})

间接导入

// test1.ets
import add from 'libentry.so'
export { add }

// test2.ets
import('./test1').then((ns:ESObject) => {
    ns.add.add(2, 3);
})

注意

不支持动态加载时,导出文件使用命名空间导出。

反例:

// test1.ets
export * from 'libentry.so'
// test2.ets
import('./test1').then((ns:ESObject) => {
    // 无法获取ns对象
})

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值