2013-11-03 70 views
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」。

欣賞任何幫助或指針。

回答

0

我看到2個問題:

  1. t.eval返回線程本身(你可以從控制檯輸出中看到)。代碼執行的結果傳遞給回調函數(如果提供了回調函數)
  2. 您需要在傳遞給eval的代碼中需要插件,閉包語義在此處不起作用。但是看起來這是不可能的:require不是在線程上下文中定義的。我認爲它是通過設計來防止競態條件問題。另請參閱https://github.com/audreyt/node-webworker-threads/issues/15
+0

因此,無法從JavaScript線程調用C++函數? –

+0

它似乎是這個特定庫的限制。但它確實有道理,因爲'require'可以用來在線程之間共享對象,這可能是不安全的。 – vkurchatkin

+0

我強烈建議不要使用任何模塊,它會在node.js中提供javascript線程。如果你想執行長時間運行的C++任務,最好使用libuv和本地線程來完成。另一種選擇是使用單獨的過程。 – vkurchatkin