【OpenHarmony】basic usage of napi----HelloWorld

Create Hello.cc file

// hello.cc using Node-API
#include <node_api.h>

namespace demo {
    
    

napi_value Method(napi_env env, napi_callback_info args) {
    
    
  napi_value greeting;
  napi_status status;

  status = napi_create_string_utf8(env, "world", NAPI_AUTO_LENGTH, &greeting);
  if (status != napi_ok) return nullptr;
  return greeting;
}

napi_value init(napi_env env, napi_value exports) {
    
    
  napi_status status;
  napi_value fn;

  status = napi_create_function(env, nullptr, 0, Method, nullptr, &fn);
  if (status != napi_ok) return nullptr;

  status = napi_set_named_property(env, exports, "hello", fn);
  if (status != napi_ok) return nullptr;
  return exports;
}

NAPI_MODULE(NODE_GYP_MODULE_NAME, init)

}  // namespace demo
  • Every node.js plugin must expose the initialization function of the following pattern:
void Initialize(Local<Object> exports);
NODE_MODULE(NODE_GYP_MODULE_NAME, Initialize)
  • module_nameExcept for the different suffixes , the parameters .nodemust match the final binary file name.
  • In the above example, the initialization function is initto module_nameuse a macro, which will ensure that the binary file name is passed as the first parameter when NODE_GYP_MODULE_NAMEthe macro is used for compilation .node-gypNODE_MODULE

create binding.gyp

{
    
    
  "targets": [
    {
    
    
      "target_name": "addon",
      "sources": [ "hello.cc" ]
    }
  ]
}
  • This file is in json format and is node-gypused by tools to compile our plugin.

compile plugin

  • node-gyp configure buildExecute and compile our plugin in our project directory .
  • After the compilation is complete, ./build/Releasethe binary file of our plug-in will be generated under the directory addon.node.

test

  • Write the test file as follows
// hello.js
const addon = require('./build/Release/addon');

console.log(addon.hello());
// Prints: 'world'
  • Execute the test file node hello.jsand it will be printed world.

full code here

おすすめ

転載: blog.csdn.net/C2681595858/article/details/127164210