我的功能init
返回v8::Handle<Object>
,此Object
包含多个Handle<Function>
属性,例如bar
。
var foo = require('foo').init({a:'a', b:'b'});
foo.bar('a');
在我的插件代码中:
Handle<Object> Bar (Arguments &args) {
// !! how to access mystruct* p for current call?
}
Handle<Object> Init(Arguments &args) {
HandleScope scope;
mystruct* p = InitMyStructWithArgs(args);
Object ret;
// !! how to bind mystruct* p to Bar?
NODE_SET_METHOD(ret, 'bar', Bar);
scope.Close(ret);
}
你看,Bar,Obj,args都是独立的,它们之间没有相关性,所以我无法在mystruct*
{}}中获得{a:'a', b:'b'}
Bar
p>
答案 0 :(得分:2)
您需要通过SetPointerInInternalField
将自定义c ++对象绑定到返回的对象。
然后,您可以通过对象函数中的GetPointerFromInternalField
访问c ++对象。
C ++
#include <v8.h>
#include <node.h>
using namespace v8;
using namespace node;
namespace {
struct Sample {
int counter;
};
Handle<Value> Add(const Arguments& args) {
HandleScope scope;
Sample *sample = static_cast<Sample*>(args.This()->GetPointerFromInternalField(0));
return scope.Close(Number::New(sample->counter));
}
Handle<Value> Init(const Arguments& args) {
HandleScope scope;
Sample* sample = new Sample();
sample->counter = 5;
Local<ObjectTemplate> objectTemplate = ObjectTemplate::New();
objectTemplate->SetInternalFieldCount(1);
Local<Object> ret = objectTemplate->NewInstance();
ret->SetPointerInInternalField(0, sample);
ret->Set(String::New("add"), FunctionTemplate::New(Add)->GetFunction());
return scope.Close(ret);
}
extern "C" void init(Handle<Object> target) {
HandleScope scope;
target->Set(String::New("init"), FunctionTemplate::New(Init)->GetFunction());
}
} // anonymous namespace
的JavaScript
var foo = test.init();
console.log(foo.add()); // 5
参考