node裏面的c/c++模塊

準備工做

node使用c++插件時須要使用node-gyp包,node-gyp把c++源碼編譯爲二進制文件,js在調用二進制文件,編譯後的二進制文件模塊調用就和js的模塊調用同樣。html

npm install -g node-gyp

除了node-gyp還須要安裝其餘準備工具。
類Unix下的準備工具
在類Unix下只需在安裝 g++工具node

sudo apt-get install g++ ;
// or
sudo yum install g++

由於在學校裏我把apt-get 配置爲學校的源,回來後用不了學校的源(貌似只能在校園網的環境下使用),而後我再修改成其餘源時只更改了地址,結果一直安裝不上,,,最後的最後才發現我修改的apt源有問題,不只須要修改地址,還要看下後面 trusty,precise仍是其它的python

// 以前的是:
deb http://**.xidian.edu.cn/ubuntu/ precise main xxxxxxxxxxxxxx

// 修改時只改了地址,安裝時就只會出錯
deb http://mirrors.163.com/ubuntu/ precise main xxxxxxxxxxxxxxxx

// 正確的是
deb http://mirrors.163.com/ubuntu/ trusty main xxxxxxxxxxxxxxxxx

Windows下準備工具
在Windows下須要安裝python和visualC++ ,python在執行configure命令時調用,vcbuild在編譯時使用
python安裝2.7版本的c++

visual C++實在是太大了,因此網上有另一種解決方式:npm

// 以管理員的身份運行   找到cmd,右鍵,以管理員身份運行;運行此命令後會安裝python2.7 和編譯工具
npm install --global --production windows-build-tools 
npm update

編寫C++模塊

由於我對C++也不熟悉,因此從官網上拿個例子下來。存爲 addon.cpp文件ubuntu

#include <node.h>
namespace demo {
using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::Object;
using v8::String;
using v8::Value;
void Method(const FunctionCallbackInfo<Value>& args) { // Method方法,使用const FunctionCallbackInfo<Value>& args接受函數參數
    Isolate* isolate = args.GetIsolate();
    args.GetReturnValue().Set(String::NewFromUtf8(isolate, "world"));
}
void init(Local<Object> exports) {
    NODE_SET_METHOD(exports, "hello", Method); // 導出模塊的hello屬性,hello屬性指向 Method方法 相似js裏的 {hello: function Method(){}}
}
NODE_MODULE(addon, init) // 注意這裏沒有分號結尾 導出模塊
}

配置與編譯

node-gyp 配置文件windows

{
    'targets': [
        {
            'target_name': 'addon', // 編譯後爲addon.node文件
            'sources': ['./addon.cc'] // 須要編譯的源碼
        }
    ]
}

node-gyp configure命令會在當前項目下生成項目文件(供編譯時使用),node-gyp build 命令調用編譯工具進行編譯,最終獲得一個node類型文件,該文件在 build/Release下,在這裏生成的是addon.node文件api

引用模塊

新建test.js文件python2.7

let addon = require('./build/Release/addon.node');
console.log(addon.hello()); // 'world'

node-gyp 命令

命令 功能
install 安裝開發文件,針對特定版本的node
list 當前安裝的工具列表
remove 移除node特定版本的開發者文件
clean 移除全部用configure和build命令生成的文件
configure 爲當前模塊生成編譯配置信息等
build 編譯當前模塊
rebuild 從新配置編譯當前模塊 至關於 clean ,configure, build的組合

c++更多示例請看官網 c/c++插件 或者百度網盤pdf版本函數

文檔裏提供了函數的參數、回調、對象工廠、函數工廠、包裝c++對象、包裝對象的工廠、傳遞包裝的對象等列子。

相關文章
相關標籤/搜索