napi hello world

2020-12-19 00:33

阅读:675

标签:exports   native   property   pen   comm   txt   ons   output   api   

目录下的文件

build-node-addon-api-with-cmake.node
CMakeLists.txt
hello.cc
hello.js
package.json

build-node-addon-api-with-cmake.nodenpm run install后生成的

npm i -D cmake-js bindings node-addon-api

cmake-js --version

CMakeLists.txt

cmake_minimum_required(VERSION 3.9)
cmake_policy(SET CMP0042 NEW)
set (CMAKE_CXX_STANDARD 11)

project (build-node-addon-api-with-cmake)
include_directories(${CMAKE_JS_INC})
file(GLOB SOURCE_FILES "hello.cc")
add_library(${PROJECT_NAME} SHARED ${SOURCE_FILES} ${CMAKE_JS_SRC})
set_target_properties(${PROJECT_NAME} PROPERTIES PREFIX "" SUFFIX ".node")
target_link_libraries(${PROJECT_NAME} ${CMAKE_JS_LIB})

# Include N-API wrappers
execute_process(COMMAND node -p "require(‘node-addon-api‘).include"
        WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
        OUTPUT_VARIABLE NODE_ADDON_API_DIR
        )
string(REGEX REPLACE "[\r\n\"]" "" NODE_ADDON_API_DIR ${NODE_ADDON_API_DIR})

target_include_directories(${PROJECT_NAME} PRIVATE ${NODE_ADDON_API_DIR})

# define NPI_VERSION
add_definitions(-DNAPI_VERSION=3)

hello.cc

#include 
#include 

static napi_value Method(napi_env env, napi_callback_info info) {
  napi_status status;
  napi_value world;
  status = napi_create_string_utf8(env, "Hello, world!", 13, &world);
  assert(status == napi_ok);
  return world;
}

#define DECLARE_NAPI_METHOD(name, func)                                          { name, 0, func, 0, 0, 0, napi_default, 0 }

static napi_value Init(napi_env env, napi_value exports) {
  napi_status status;
  napi_property_descriptor desc = DECLARE_NAPI_METHOD("hello", Method);
  status = napi_define_properties(env, exports, 1, &desc);
  assert(status == napi_ok);
  return exports;
}

NAPI_MODULE(hello, Init)

hello.js

var addon = require(‘bindings‘)(‘build-node-addon-api-with-cmake‘);

console.log(addon.hello()); // ‘world‘

package.json

{
  "name": "build-node-addon-api-with-cmake",
  "version": "0.0.0",
  "description": "Build N-API native addon with CMake and node-addon-api C++ wrapper.",
  "main": "hello.js",
  "private": true,
  "dependencies": {},
  "scripts": {
    "install": "cmake-js compile",
    "test": "node hello.js"
  },
  "devDependencies": {
    "bindings": "^1.2.1",
    "cmake-js": "^6.1.0",
    "node-addon-api": "^1.7.2"
  }
}

napi hello world

标签:exports   native   property   pen   comm   txt   ons   output   api   

原文地址:https://www.cnblogs.com/Searchor/p/13925274.html


评论


亲,登录后才可以留言!