1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
| . └── caddon ├── binding.gyp ├── build ├── calculate1.cc ├── calculate.cc ├── hello.cc ├── hello.js ├── main.js ├── package.json └── README.md
binding.gyp
{ "targets": [ { "target_name": "calculate", "sources": [ "calculate.cc" ] }, { "target_name": "calculate1", "sources": [ "calculate1.cc" ] }, { "target_name": "hello", "sources": [ "hello.cc" ] } ]
}
calculate1.cc
#include <node.h>
namespace calculate1 { using v8::FunctionCallbackInfo; using v8::Isolate; using v8::Local; using v8::Object; using v8::Number; using v8::Value; using v8::String; using v8::Exception;
void Method(const FunctionCallbackInfo<Value>&args) { Isolate* isolate = args.GetIsolate();
// 检查参数数量 if (args.Length() < 2) { isolate->ThrowException(Exception::TypeError( String::NewFromUtf8(isolate, "Wrong number of arguments").ToLocalChecked())); return; }
if (!args[0]->IsNumber() || !args[1]->IsNumber()) { isolate->ThrowException(Exception::TypeError( String::NewFromUtf8(isolate, "Wrong arguments").ToLocalChecked())); return; }
int x = args[0]->NumberValue(isolate->GetCurrentContext()).FromJust(); int y = args[1]->NumberValue(isolate->GetCurrentContext()).FromJust();
int i; // double x = 100.734659, y = 353.2313423432; for (i=0; i < 100; i++) { x += y; } auto total = Number::New(isolate, x); args.GetReturnValue().Set(total); }
void Initialize(Local<Object> exports) { NODE_SET_METHOD(exports, "calc1", Method); } NODE_MODULE(NODE_GYP_MODULE_NAME, Initialize) }
main.js
const calculate = require('./build/Release/calculate') const calculate1 = require('./build/Release/calculate1') const hello = require('./build/Release/hello') const hello_js = require('./hello.js')
function calc() { let i, x = 100.734659, y=353.2313423432; for (i=0; i<1000000000; i++) { x += y; } const total = x return total } console.log('c++ addon result vs Node result') console.log('C++ :' + calculate.calc()) console.log('Node :' + calc()) console.log('---------------------------------------') console.log('c++ addon vs js addon') console.log(hello.hello()) console.log(hello_js('Jack Yeh'))
console.log('c++ addon')
console.log('C++ :' + calculate1.calc1(100, 100))
更多参考:https://github.com/wangzhiwei1888/cpp_node_modules.git
|