1
我在我的javascript代碼中創建了一個web工作線程。我正在嘗試使用node-gyp和V8從線程中調用C++函數。但我無法讓它工作。從網絡工作者線程調用C++ v8函數
下面是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」。
欣賞任何幫助或指針。
因此,無法從JavaScript線程調用C++函數? –
它似乎是這個特定庫的限制。但它確實有道理,因爲'require'可以用來在線程之間共享對象,這可能是不安全的。 – vkurchatkin
我強烈建議不要使用任何模塊,它會在node.js中提供javascript線程。如果你想執行長時間運行的C++任務,最好使用libuv和本地線程來完成。另一種選擇是使用單獨的過程。 – vkurchatkin