栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

使用cmake-js编译NodeJS C++插件

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用cmake-js编译NodeJS C++插件

使用cmake-js编译NodeJS C++插件

如需转载请标明出处:http://blog.csdn.net/itas109
QQ技术交流群:129518033

文章目录
  • 使用cmake-js编译NodeJS C++插件
    • 1. 安装cmake-js
    • 2. 编写addon.cpp
    • 3. 编写CMakeLists.txt
    • 4. 编译.node
    • 5. 编写index.js测试.node

1. 安装cmake-js
  • 在线安装
$npm i -g cmake-js

查看cmake-js帮助

$ cmake-js -h
  • 离线安装

头文件下载
https://nodejs.org/dist/v12.13.0/node-v12.13.0-headers.tar.gz

库文件下载(仅windows)
https://nodejs.org/dist/v12.13.0/win-x64/node.lib

linux

~/.cmake-js/node-x64/v12.13.0/include
$ tree
.cmake-js
└── node-x64
    └── v12.13.0
        └── include
            └── node

windows

~/.cmake-js/node-x64/v12.13.0/include
$ tree
.cmake-js
+--- node-x64
|   +--- v12.13.0
|   |   +--- include
|   |   |   +--- node
|   |   +--- win-x64
|   |   |   +--- node.lib
2. 编写addon.cpp

addon.cpp

#include 
#include 

static napi_value helloMethod(napi_env env, napi_callback_info info)
{
    napi_status status;
    napi_value result;

    status = napi_create_string_utf8(env, "hello world", 11, &result);
    assert(status == napi_ok);

    return result;
}

static napi_value Init(napi_env env, napi_value exports)
{
    napi_status status;
    napi_property_descriptor desc = {"hello", 0, helloMethod, 0, 0, 0, napi_default, 0};

    status = napi_define_properties(env, exports, 1, &desc);
    assert(status == napi_ok);

    return exports;
}

NAPI_MODULE(NODE_GYP_MODULE_NAME, Init)
3. 编写CMakeLists.txt

CMakeLists.txt

cmake_minimum_required(VERSION 2.8)

project(addon)

message(STATUS "operation system is ${CMAKE_SYSTEM}")

#add_compile_options(-g)

# 设置头文件路径
include_directories(${CMAKE_JS_INC})
include_directories(.)

# 源文件列表
file(GLOB SOURCE_FILES addon.cpp)

# 生成.node文件
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})
4. 编译.node
$ cmake-js configure build -D
5. 编写index.js测试.node

index.js

'use strict';

const addon = require('bindings')('addon');

console.log(addon.hello()); // 'hello world'
$ node index.js
hello world

License

License under CC BY-NC-ND 4.0: 署名-非商业使用-禁止演绎

如需转载请标明出处:http://blog.csdn.net/itas109
QQ技术交流群:129518033


Reference:

  1. NULL
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/444018.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号