Symptom
The default C++ project created in DevEco Studio has only one hello.cpp file. How do I add an a.cpp file in C++ and export the APIs from a.cpp for ArkTS to call?
Solution
Include the header file a.h of a.cpp, map the APIs in Init(), and export the APIs from the index.d.ts file.
Sample code:
Implement the Add() function in the NumberType.cpp file.
#include "NumberType.h" // Import header file
// NumberType is the class name, and Add is its function
napi_value NumberType::Add(napi_env env, napi_callback_info info) {
// ... Business Function Implementation Code
// ...
} Include the header file to hello.cpp and map the native and ArkTS APIs in Init().
#include "NumberType.h"
#include "napi/native_api.h"
EXTERN_C_START
static napi_value Init(napi_env env, napi_value exports)
{
/* Associate the externally provided interface with the written method, for example, associate add with the Add
* method.
*/
napi_property_descriptor desc[] = {
{ "add", nullptr, NumberType::Add, nullptr, nullptr, nullptr, napi_default, nullptr }
};
// napi_define_properties construct a return value that contains a list of methods that correspond.
napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);
return exports;
}
EXTERN_C_END Export the API to ArkTS from the API declaration file index.d.ts.
export const add: (a: number, b: number) => number;
Reference