我的函数 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
最佳答案
例子
您需要通过 SetPointerInInternalField
将您的自定义 C++ 对象绑定(bind)到您返回的对象。
然后您可以通过对象函数中的 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
引用
关于c++ - 如何在没有 OO 的情况下关联值(value)和功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8553936/