zoukankan      html  css  js  c++  java
  • Node.js Addons翻译(C/C++扩展)

    PS:请先升级Node 6.2.1,Node 升级命令 npm install -g n;n stable.NOde.js扩展是一个通过C/C++编写的动态链接库,并通过Node.js的函数require()函数加载,用起来就像使用一个普通的Node.js模块。它主要为Node与C/C++库之间提供接口。
    这样,若一个方法或函数是通过Node扩展实现则变得相当复杂,涉及几个模块与接口的知识:

    • v8:一个实现了通过C++库实现了的javascript.V8提供了创建对象机制,回调函数等。V8API文档大多在v8.h头文件中。点我v8在线文档
    • libuv:一个实现了Node.js的工作线程和异步行为的平台的事件循环的C库。它还充当了一个跨平台的抽象库,可以简单地POSIX-like式的访问所有主流操作系统系统许多常见任务,例如与文件系统交互、套接字、定时器和系统事件。libuv还提供了一个抽象pthreads-like线程,可以用于更复杂的异步。Node.js的C/C++扩展需要超越标准事件循环。插件作者鼓励去思考如何避免阻塞I/O事件循环和通过libuv非阻塞系统操作、工作线程、用户自定义的线程完成任务密集型工作。
    • Node.js内置库:Node.js本身使用了大量的C/C++扩展的API,C/C++扩展时最重要的一个类node:ObjectWrap
    • Node.js众多的静态链接库如OpenSSL:Node.js的其它的库在它的源码目录树下的 deps目录。详情请见·Node.js's own dependencies for additional information。点我Node.js官方扩展库示例,这也许是你为Node.js编写C/C++扩展库的起点。只有V8和OpenSSL类经常在Node C/C++扩展中频繁的使用。

    Node C/C++扩展第一弹-最新示例Hello World

    该示例适用Node.js版本号为V5.0以上。

    // hello.js
    const addon = require('./build/Release/addon');
    
    console.log(addon.hello()); // 'world'
    
    
    // hello.cc
    #include <node.h>
    #include <v8.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) {
      Isolate* isolate = args.GetIsolate();
      args.GetReturnValue().Set(String::NewFromUtf8(isolate, "world"));
    }
    
    void init(Local<Object> exports) {
      NODE_SET_METHOD(exports, "hello", Method);
    }
    
    NODE_MODULE(addon, init)
    
    }  // namespace demo
    
    // binding.gyp
    {
      "targets": [
        {
          "target_name": "addon",
          "sources": [ "hello.cc" ]
        }
      ]
    }
    

    node-gyp命令

    node-gyp configure build
    
  • 相关阅读:
    ABP初始化
    ABP生成错误:必须添加对程序集“netstandard”的引用
    树莓派安装Mysql
    多对多关系的中间表命名
    dapper.net 存储过程
    Rabbitmq发送方消息确认
    Rabbitmq发送消息Message的两种写法
    ThreadLocal原理
    多模块打包为可执行jar问题
    类中属性加载顺序的demo
  • 原文地址:https://www.cnblogs.com/orangebook/p/5576641.html
Copyright © 2011-2022 走看看