栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

nodejs 写c++插件的实例

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

nodejs 写c++插件的实例

前提描述

为了方便计算数据库中数据,如我们睡眠床的心率并计算心率变异率而做,用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() < 2) {
   	  // Throw an Error that is passed back to Javascript
   	  isolate->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));


结果如图所示

转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号