gpt4 book ai didi

c++ - 从 Web 工作线程调用 C++ v8 函数

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:55:39 25 4
gpt4 key购买 nike

我在我的 javascript 代码中创建了一个网络工作线程。我正在尝试使用 node-gyp 和 V8 从线程调用 C++ 函数。但我无法让它工作。

这是 hello.cc 的代码

#include <v8.h>

using namespace v8;
extern std::string myhello();
Handle<Value> Method(const Arguments& args) {
HandleScope scope;
return scope.Close(String::New("hello"));
}

void init(Handle<Object> exports) {
exports->Set(String::NewSymbol("hello"),
FunctionTemplate::New(Method)->GetFunction()
);
}

NODE_MODULE(hello, init)

这是 myhello.js 的代码

var addon = require('./build/Release/hello');
var thread = require('webworker-threads');

var t = thread.create();
console.log(t.eval("addon.hello()"));

当我运行 node myhello.js 时,我得到以下输出

{ id: 0,
eval: [Function: eval],
load: [Function: load],
emit: [Function: emit],
emitSerialized: [Function: emitSerialized],
destroy: [Function: destroy],
on: [Function],
once: [Function],
removeAllListeners: [Function],
dispatchEvents: [Function],
_on: {} }

我希望在控制台上打印“hello”。

感谢任何帮助或指点。

最佳答案

我看到 2 个问题:

  1. t.eval 返回线程本身(正如您从控制台输出中看到的那样)。代码执行的结果传递给回调,如果提供的话
  2. 您需要在传递给 eval 的代码中 require addon,闭包语义在这里不起作用。但看起来这是不可能的:require 没有在线程上下文中定义。我认为这是为了防止竞争条件问题而设计的。另见 https://github.com/audreyt/node-webworker-threads/issues/15

关于c++ - 从 Web 工作线程调用 C++ v8 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19759046/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com