addon 历史:https://xcoder.in/2017/07/01/nodejs-addon-history/ 直接调用 // 目前 neon 使用 V8 API 与 JS 运行时进行所有 JS 交互 Native Abstractions for Node.js N-API // ABInode可以重载模块,使用require.cache // c/c++的不能使用node 的 --inspect 参数时 文件运行结束后 全局对象中 没有require,cache在Module构造函数的_cache 中。APIs 包括:V8: the C++ library Node.js currently uses to provide the JavaScript implementation. libuv: The C library that implements the Node.js event loop, its worker threads and all of the asynchronous behaviors of the platform.Internal Node.js libraries. the most important of which is the node::ObjectWrap class.Node.js includes a number of other statically linked libraries including OpenSSL. 基本步骤:// sudo npm install node-gyp -g编写源文件 和 .gyp 文件(类json,指定源文件和目标文件名)node-gyp rebuild // 相当于 configure + build构建的二进制文件位于 ./build/Release 下require('./build/Release/addon.node')基本使用: C++导出,C++接受参数const FunctionCallbackInfo<Value>& args // 获得js实参引用 Isolate* isolate = args.GetIsolate(); // 映射到指针 Local<Function> cb = Local<Function>::Cast(args[0]); // 获取js实参函数 const unsigned argc = 1; // Call中的第二个参数必须是1 ,表示cb的实参(第三个参数数组)长度 Local<Value> argv[argc] = { String::NewFromUtf8(isolate, "hello world") }; // argv是一个1长度的数组,{} 数组内有一个元素 cb->Call(Null(isolate), argc, argv); //执行js传入的函数 Local<Object> obj = Object::New(isolate); // 修改指针指向的引用为对象obj obj->Set(String::NewFromUtf8(isolate, "msg"), args[0]->ToString()); // 在obj对象上设置一个msg属性 Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, MyFunction); // 新建函数模板 Local<Function> fn = tpl->GetFunction(); // 从函数模板生成函数 fn->SetName(String::NewFromUtf8(isolate, "theFunction")); // 设置函数为匿名 args.GetReturnValue().Set(String::NewFromUtf8(isolate, "world")); // 修改指针指向的引用 并作为返回值 isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Wrong number of arguments"))); //传递错误到 jsLocal<Object> exports // 引入node exports对象 NODE_SET_METHOD(exports, "hello", Method); // 设置exports 的属性NODE_MODULE(addon, init) //没有分号,他不是一个函数,必须加这行
Tags
nodejs
Created
Jul 7, 2016 9:48 AM