Skip to content
This repository was archived by the owner on Feb 27, 2022. It is now read-only.
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 19 additions & 6 deletions nas.cc
Original file line number Diff line number Diff line change
Expand Up @@ -17,25 +17,30 @@ extern "C" void init (Handle<Object>);
struct simple_request {
int x;
int y;
char *name;
Persistent<Function> cb;
// maybe it matters to put the char[] last? not sure.
char name[1];
};

static Handle<Value> DoSomethingAsync (const Arguments& args) {
HandleScope scope;
const char *usage = "usage: doSomething(x, y, name, cb)";

// validate argument count
if (args.Length() != 4) {
return ThrowException(Exception::Error(String::New(usage)));
}

// read arguments
int x = args[0]->Int32Value();
int y = args[1]->Int32Value();
String::Utf8Value name(args[2]);
Local<Function> cb = Local<Function>::Cast(args[3]);

simple_request *sr = (simple_request *)
malloc(sizeof(struct simple_request) + name.length() + 1);
// init request
simple_request *sr = new simple_request();
sr->name = new char[name.length() + 1];

// assign arguments to request fields
sr->cb = Persistent<Function>::New(cb);
strncpy(sr->name, *name, name.length() + 1);
sr->x = x;
Expand All @@ -58,22 +63,30 @@ static int DoSomething (eio_req *req) {
static int DoSomething_After (eio_req *req) {
HandleScope scope;
ev_unref(EV_DEFAULT_UC);

struct simple_request * sr = (struct simple_request *)req->data;

Local<Value> argv[3];
argv[0] = Local<Value>::New(Null());
argv[1] = Integer::New(req->result);
argv[2] = String::New(sr->name);

//call callback
TryCatch try_catch;
sr->cb->Call(Context::GetCurrent()->Global(), 3, argv);
if (try_catch.HasCaught()) {
FatalException(try_catch);
}

// cleanup
sr->cb.Dispose();
free(sr);
delete[] sr->name;
delete sr;

return 0;
}

extern "C" void init (Handle<Object> target) {
HandleScope scope;
NODE_SET_METHOD(target, "doSomething", DoSomethingAsync);
}
}