前提描述
为了方便计算数据库中数据,如我们睡眠床的心率并计算心率变异率而做,用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));
结果如图所示