我正在寻找一种方法来为当前版本 (0.5.9) 的 NodeJs 构建 c++ 模块。 通过使用以下教程并从 Node node_file.cc 中抽象出来,我能够自己为 Node 0.5.3 构建一个模块。
但是在 Node 0.5.4 中,一些 API 肯定发生了变化,因为我不再能够使用 eio_* 扭曲函数了。
查看 node_file.cc 我发现 eio_* 包装已被新的 ReqWrap 类替换。
例如在这个宏中:https://gist.github.com/1303926
不,我想知道编写异步扩展的最佳方式是什么?
最佳答案
基本上看加密 Node 模块解决了我的问题,这个模块没有像文件模块这样的宏被污染。我想出了一个简单的异步模块来计算两个整数的和:
#include <v8.h>
#include <node.h>
#include <stdlib.h>
#include <errno.h>
using namespace node;
using namespace v8;
struct Test_req
{
ssize_t result;
ssize_t int1;
ssize_t int2;
Persistent<Function> callback;
};
void TestWorker(uv_work_t* req)
{
Test_req* request = (Test_req*)req->data;
request->result = request->int1 + request->int2;
}
void TestAfter(uv_work_t* req)
{
HandleScope scope;
Test_req* request = (Test_req*)req->data;
delete req;
Handle<Value> argv[2];
// XXX: Error handling
argv[0] = Undefined();
argv[1] = Integer::New(request->result);
TryCatch try_catch;
request->callback->Call(Context::GetCurrent()->Global(), 2, argv);
if (try_catch.HasCaught())
{
FatalException(try_catch);
}
request->callback.Dispose();
delete request;
}
static Handle<Value> Test(const Arguments& args)
{
HandleScope scope;
if ( args.Length() < 3 || !args[0]->IsNumber() || !args[1]->IsNumber() )
{
return ThrowException(Exception::TypeError(String::New("Bad argument")));
}
ssize_t int1 ( args[0]->Int32Value() );
ssize_t int2 ( args[1]->Int32Value() );
if ( args[2]->IsFunction() )
{
Local<Function> callback = Local<Function>::Cast(args[2]);
Test_req* request = new Test_req;
request->callback = Persistent<Function>::New(callback);
request->int1 = int1;
request->int2 = int2;
uv_work_t* req = new uv_work_t();
req->data = request;
uv_queue_work(uv_default_loop(), req, TestWorker, TestAfter);
}
else
{
return ThrowException(Exception::TypeError(String::New("Callback missing")));
}
return Undefined();
}
extern "C"
{
static void init(Handle<Object> target)
{
HandleScope scope;
}
}
NODE_MODULE(node_AsyncTest, init);
在 Node 端,您可以这样调用模块:
var foo = process.binding('AsyncTest');
foo.Test(1,2,function(err,data){
console.log(err,data);
});
结果:
undefined 3
希望这会有所帮助;)
Ps:由于windows下缺少node编译扩展。我正在使用 Visual Studio 构建解决方案将其直接构建到 Node Windows 端口的核心中。
关于javascript - 编写 ASYNC CPP nodejs (0.5.3+) 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7850600/