c++ - 如何在没有 OO 的情况下关联值(value)和功能

标签 c++ design-patterns node.js v8

我的函数 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

引用

http://izs.me/v8-docs/classv8_1_1ObjectTemplate.html

关于c++ - 如何在没有 OO 的情况下关联值(value)和功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8553936/

相关文章:

design-patterns - java,单例泛化

c++ - windows上的linux开发

c++ - 从继承类调用匹配方法

c++ - 将文件存储在 TEMP 目录中是否足够安全

node.js - 使用 "export * as"语法的node_modules软件包中的 typescript 错误

node.js - 正在运行的nodejs应用程序能否以加密方式证明它与已发布的源代码版本相同?

json - 如何通过node js向现有的json文件添加子 Node ?

c++ - 奇怪的 std::sort 行为

design-patterns - 数据映射器在领域驱动设计模式中相互调用

php - 在php中使用策略模式的优点