diff --git a/nas.cc b/nas.cc index cd68f7b..1bb971e 100644 --- a/nas.cc +++ b/nas.cc @@ -17,25 +17,30 @@ extern "C" void init (Handle); struct simple_request { int x; int y; + char *name; Persistent cb; - // maybe it matters to put the char[] last? not sure. - char name[1]; }; static Handle 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 cb = Local::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::New(cb); strncpy(sr->name, *name, name.length() + 1); sr->x = x; @@ -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 argv[3]; argv[0] = Local::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 target) { HandleScope scope; NODE_SET_METHOD(target, "doSomething", DoSomethingAsync); -} +} \ No newline at end of file