Node Addon
Node Addon as bridge between javascript and C++
#include <node.h>
namespace HelloWorldDemo {
using v8::FunctionCallbackInfo; //used for passing arguments and returning val
using v8::Isolate; //v8 VM which has memory heap
using v8::Local; //Local is template of handle, Local<ClassType> means handle of ClassType
using v8::Object;
using v8::String;
using v8::Value;
using v8::Null;
using v8::Number;
using v8::Function;
using v8::Exception;
using v8::FunctionTemplate;
//hello method
void hello (const FunctionCallbackInfo<Value>& args) {
//get v8 VM
Isolate* isolate = args.GetIsolate();
//create js string "hello world" in v8 VM heap
args.GetReturnValue().Set(String::NewFromUtf8(isolate, "hello world."));
}
//accumulate method
void accumulate (const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
/*throw exception*/
if (args.Length() < ) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate, "Arguments Number Error.")
));
return;
}
/*throw exception*/
if (!args[args.Length() - ]->IsFunction()) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate, "No Callback Error.")
));
return;
}
//get callback function from js
Local<Function> callback = Local<Function>::Cast(args[args.Length() - ]);
//accumulate
double sum = 0.0;
for (int i = ; i < args.Length() - ; ++i) {
/* throw exception if invalid number */
if (!args[i]->IsNumber()) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate, "Arguments Type Error.")
));
return;
} else {
sum += args[i]->NumberValue();
}
}
//call callback with accumulated result
Local<Number> num = Number::New(isolate, sum);
Local<Value> argv[] = { num };
callback->Call(Null(isolate), , argv);
}
//return obj
void getPerson (const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
//create object
Local<Object> obj = Object::New(isolate);
//set (key,val) to object
obj->Set(
String::NewFromUtf8(isolate, "firstname"),
String::NewFromUtf8(isolate, "Java")
);
obj->Set(
String::NewFromUtf8(isolate, "lastname"),
String::NewFromUtf8(isolate, "Script")
);
//return object to js
args.GetReturnValue().Set(obj);
}
//pass object to C++
void sayHiTo (const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
//get object from js
Local<Object> person = Local<Object>::Cast(args[]);
//get value from object
Local<String> fullname = String::Concat(
person->Get(String::NewFromUtf8(isolate, "firstname"))->ToString(),
person->Get(String::NewFromUtf8(isolate, "lastname"))->ToString()
);
//return value to js
args.GetReturnValue().Set(String::Concat(
String::NewFromUtf8(isolate, "Hi, "),fullname
));
}
//return function
void getFunction (const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
//create js function
Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, sayHiTo);
Local<Function> fn = tpl->GetFunction();
fn->SetName(String::NewFromUtf8(isolate, "sayHiTo"));
//return function to js
args.GetReturnValue().Set(fn);
}
//initializtion function which is called when module is loaded into NodeJS for first time
void init (Local<Object> exports) {
/* exports method hello */
/* same as javascript's module.exports.hello = hello */
/* NODE_SET_METHOD can have many */
NODE_SET_METHOD(exports, "hello", hello);
NODE_SET_METHOD(exports, "accumulate", accumulate);
NODE_SET_METHOD(exports, "getPerson", getPerson);
NODE_SET_METHOD(exports, "getFunction", getFunction);
}
//macro, set initializtion method of module
NODE_MODULE(NODE_GYP_MODULE_NAME, init)
}
//build addon
file: binding.gyp
{
"targets": [
{
"target_name": "myaddon",
"sources": ["hello.cc"]
},{
"target_name": "accumulate",
"sources": ["accumulate.cc"]
}]
}
command:
node-gyp configure
node-gyp build
Using:
const myaddon = require('./build/Release/myaddon')
console.log('[HelloWorldDemo]' + myaddon.hello())
myaddon.accumulate(1, 3, 4, 7, (sum) => {
console.log('[FunctionArgumentsAndCallbacksDemo] 1 + 3 + 4 + 7 = ' + sum)
})
try {
myaddon.accumulate(1, 2, 'a', (sum) => {
console.log(sum)
})
} catch (err) {
console.log('[ExceptionDemo] ' + err)
}
let someone = myaddon.getPerson()
console.log('[ReturnObjectDemo] ' + someone.firstname + someone.lastname)
// return-function demo
let sayHiTo = myaddon.getFunction()
console.log('[ReturnFunctionDemo] ' + sayHiTo(someone))
Node Addon的更多相关文章
- ACK容器服务发布virtual node addon,快速部署虚拟节点提升集群弹性能力
在上一篇博文中(https://yq.aliyun.com/articles/647119),我们展示了如何手动执行yaml文件给Kubernetes集群添加虚拟节点,然而,手动执行的方式用户体验并不 ...
- Node.js 自学之旅
学习基础,JQuery 原生JS有一定基础,有自己一定技术认知(ps:原型链依然迷糊中.闭包6不起来!哎!) 当然最好有语言基础,C#,java,PHP等等.. 最初学习这个东西的原因很简单,在园子里 ...
- 使用neon 开发nodejs addon
备注:开发使用的是mac 系统,需要安装rust nodejs .python2.7 Xcode 1. 安装neon npm install -g neon-cli 2. 创建简单项目 neon ...
- Node.js 自学之旅(初稿篇)
学习基础,JQuery 原生JS有一定基础,有自己一定技术认知(ps:原型链依然迷糊中.闭包6不起来!哎!) 当然最好有语言基础,C#,java,PHP等等.. 最初学习这个东西的原因很简单,在园子里 ...
- nodejs 后台开发 和C++代码开发
https://www.npmjs.com/package/node-gyp node-gyp Node.js native addon build tool Node.js native addon ...
- nodejs与c语言交互应用实例
nodejs与c/c++交互目前主流的方式有两种,node addon c++ 和 node-ffi . 1.node addon c++ 1)nodejs从c语言读取数据 addon.c #incl ...
- Appium 教您完美win10安装Appium1.7.2支持win客户端自动化
参考内容: https://testerhome.com/topics/10193https://testerhome.com/topics/8223https://testerhome.com/to ...
- ACK容器服务虚拟节点使用阿里云日志服务来收集业务容器日志
按照这篇博文的介绍,可以在ACK集群上通过Helm的方式部署虚拟节点,提升集群的弹性能力.现在,通过虚拟节点部署的ECI弹性容器实例也支持将stdout输出.日志文件同步到阿里云日志服务(SLS)进行 ...
- babeljs源码
babel.min.js!function(e,t){"object"==typeof exports&&"object"==typeof mo ...
随机推荐
- 笔记本端查看以前的wifi密码
家里老人忘记密码了.好像是我改了从,我也忘了,手中安卓手机root后也没找到记录密码的文件,水果机懒得弄了,突然想起来电脑还有记录,应该可以找到. 此篇也顺带记录下怎么通过手中笔记本找到以前练过的wi ...
- 想知道使用OPC服务器时如何设置DCOM?看完本文就懂了(下)
接上文...... “安全”选项卡“安全”选项卡上,有3个选项需要设置. 启动权限 选择“使用默认值”选项 访问权限 选择“使用默认值”选项 配置权限 选择“自定义”选项,然后单击“编辑” 将打开一个 ...
- docker实战 (3) 常规配置
本节会持续更新,在项目实战中遇到的docker配置都会更新进来 docker常用命令: docker 介绍: what: 是什么 why: 为什么用 how: 怎么用 docker 特点: 轻量级,可 ...
- Kubectl Rollout 回滚及Autoscale自动扩容
Kubectl Rollout 回滚及Autoscale自动扩容 Kubernetes 中采用ReplicaSet(简称RS)来管理Pod.如果当前集群中的Pod实例数少于目标值,RS 会拉起新的Po ...
- 【MySQL】FIND_IN_SET、LIKE、IN的区别
现在有张新闻表,里面有新闻名称name字段,有新闻类型type字段,1代表头条,2代表推荐,11代表热点,22代表最新,现在表中有两条记录,存储形式如下,现在的需求是查找头条新闻,及type中包含1的 ...
- 个人第五次作业-alpha2测试
课程属于课程 课程链接 作业要求 作业要求链接 团队名称 你的代码我的发 https://www.cnblogs.com/skrchou/p/11885706.html 测试人名称 颜依婷 测试人学号 ...
- 记录第n次网站渗透经历
如标题所示,第x次实战获取webshell的经历是非常美好且需要记录的(毕竟开始写博客了嘛).这能够证明这一路来的学习没有白费,也应用上了该用的知识. 首先怎么说呢,某天去补天看了看漏洞,发现有一个网 ...
- Reprint: CMake or Make
CMake vs Make https://prateekvjoshi.com/2014/02/01/cmake-vs-make/ Programmers have been using CMake ...
- php中函数的类型提示和文件读取功能
这个没有深入. <?php function addNumbers(int $a, int $b, bool $printSum): int { $sum = $a + $b; if ($pri ...
- The 16th Zhejiang Provincial Collegiate Programming Contest Sponsored by TuSimple (Mirror)
B题 思路 因为 \[ x=\sum\limits_{k=1}^{n}ka_k\\ y=\sum\limits_{k=1}^{n}ka_{k}^{2} \] 我们设交换前和交换后的这两个等式的值设为\ ...