您当前的位置: 首页 >  c++

qianbo_insist

暂无认证

  • 0浏览

    0关注

    399博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

nodejs 写c++插件的实例

qianbo_insist 发布时间:2021-12-20 17:11:18 ,浏览量:0

前提描述

为了方便计算数据库中数据,如我们睡眠床的心率并计算心率变异率而做,用c++ 写基本的算法,隔一段时间会更新算法,每次更新动态库即可

准备工作

1 安装python3.6 以上的python版本 注意path里面必须有python-srcipt和python的路径,如果有python2.7,删除掉重新安装 2 安装编译工具链 npm install -g node-gyp

编写binging.gyp
{
 'targets':[
 {
 'target_name':'hrv',
 'sources':['hrv.cc'],
 }]
}
编写代码

一个例子函数,一个加法函数

 #include 
  namespace demo {
 using v8::Exception;
 using v8::FunctionCallbackInfo;
 using v8::Isolate;
 using v8::Local;
 using v8::Number;
 using v8::Object;
 using v8::String;
 using v8::Value;

 void Method(const FunctionCallbackInfo& args) {
     Isolate* isolate = args.GetIsolate();
     args.GetReturnValue().Set(String::NewFromUtf8(
   	  isolate, "world").ToLocalChecked());
 }
 void Method1(const FunctionCallbackInfo& args) {
     Isolate* isolate = args.GetIsolate();
     args.GetReturnValue().Set(String::NewFromUtf8(
   	  isolate, "world").ToLocalChecked());
 }
 void calc(const FunctionCallbackInfo& args) {
     Isolate* isolate = args.GetIsolate();

     // Check the number of arguments passed.
     if (args.Length() ThrowException(Exception::TypeError(
   		  String::NewFromUtf8(isolate,
   			  "Wrong number of arguments").ToLocalChecked()));
   	  return;
     }

     // Check the argument types
     if (!args[0]->IsNumber() || !args[1]->IsNumber()) {
   	  isolate->ThrowException(Exception::TypeError(
   		  String::NewFromUtf8(isolate,
   			  "Wrong arguments").ToLocalChecked()));
   	  return;
     }

     // Perform the operation
     double value =
   	  args[0].As()->Value() + args[1].As()->Value();
     Local num = Number::New(isolate, value);

     // Set the return value (using the passed in
     // FunctionCallbackInfo&)
     args.GetReturnValue().Set(num);
 }

 void init(Local exports) {

 NODE_SET_METHOD(exports, "hrv", Method);
 NODE_SET_METHOD(exports, "calc", calc);
 }


 NODE_MODULE(NODE_GYP_MODULE_NAME, init)

 }

写完以后,编译: node-gyp configure node-gyp build 生成文件 在这里插入图片描述

在这里插入图片描述 生成了hrv.node

测试

写nodejs脚本 const addon = require(’./build/Release/hrv’);

console.log(addon.hrv()); // ‘world’ console.log(addon.calc(10, 11));

在这里插入图片描述 结果如图所示

关注
打赏
1663161521
查看更多评论
立即登录/注册

微信扫码登录

0.0358s