|
在 addon.cc 模式里,你能用 C++ 函数创建并返回一个新的对象,这个对象所包含的 msg 属性是由createObject() 函数传入:
- // addon.cc
- #include <node.h>
- using namespace v8;
- void CreateObject(const FunctionCallbackInfo<Value>& args) {
- Isolate* isolate = Isolate::GetCurrent();
- HandleScope scope(isolate);
- Local<Object> obj = Object::New(isolate);
- obj->Set(String::NewFromUtf8(isolate, "msg"), args[0]->ToString());
- args.GetReturnValue().Set(obj);
- }
- void Init(Handle<Object> exports, Handle<Object> module) {
- NODE_SET_METHOD(module, "exports", CreateObject);
- }
- NODE_MODULE(addon, Init)
复制代码 使用 JavaScript 测试:
- // test.js
- var addon = require('./build/Release/addon');
- var obj1 = addon('hello');
- var obj2 = addon('world');
- console.log(obj1.msg+' '+obj2.msg); // 'hello world'
复制代码
|
|