Using libuv inside classes

I am trying to write nodejs bindings for a C ++ library and it looks like I ended up in a roadblock.

I am working on an attempt to make all calls in the C ++ library asynchronous, and therefore I use libuv . I mainly follow this tutorial.

I want to be able to call member class functions from libuv uv_queue_work . Look at this code -

 class test { private: int data; void Work(uv_work_t *req); void After(uv_work_t *req); public: Handle<Value> Async(const Arguments& args) { HandleScope scope; Local<Function> callback = Local<Function>::Cast(args[0]); int status = uv_queue_work(uv_default_loop(), **something**, Work, After); assert(status == 0); return Undefined(); } }; 

Basically, I expect the Work and After functions to work with the data element of the class. However, this does not seem to work. I tried casting pointer types to Work and After after the type void test::(*)(uv_work_t*) in void (*)(uv_work_t*) . But that doesn't work either.

Could you guys give me some tips on how to get around this?

+4
source share
1 answer

So, as you understand, you cannot directly call member functions.

The second argument is something "of type uv_work_t, which has the element" void * data ".

What you need to do is create static methods inside your class for "Work" and "After", create a uv_work_t structure and assign the data "this".

After this is done inside your static "Work" and "After" methods, you perform a static conversion to "req-> data" (To your class type), and then call your member functions.

For instance:

 uv_work_t* baton = new uv_work_t(); baton->data = this; int status = uv_queue_work(uv_default_loop(), baton, StaticWork, StaticAfter); 

And then in static methods

 test* myobj = static_cast<test>(req->data); myobj->Work(); 

And similar code for StaticAfter function

+6
source

All Articles