Calling C callback from Ruby using SWIG
I'm trying to create bindings for a C library to Ruby via SWIG (2.0.3). Say, we have a function prototype in C that reads:
void do_sth_and_call_me_then( (int)(* my_callback)(GlyQuery *, GlyMemCache *))
This will do some strange things and eventually calls the callback:
int my_callback(GlyQuery * a, GlyMemCache * b)
given as paramter several times. As this is the usua开发者_StackOverflowl way to talk with the library I want to have this behaviour in Ruby too. While researching I found this, which is pretty much what I need:
%{
void
wrap_callback(void *user_data, const char *other_data)
{
VALUE proc = (VALUE)user_data;
rb_funcall(proc, rb_intern("call"), 1, rb_str_new2(other_data));
}
%}
Sadly I can't figure out what I have to change to make this to work with objects other than strings.
If you need more information: the whole interface file is here
Any advice? Thanks for any help.
You should create a wrapper of callback function, as C library can't call a ruby function directly.
In this wrapper you should convert Structs into something you can pass to ruby code, because ruby can't work directly with C structs.
There is a solutionm which allows ruby code to access C structs, described here Wrapping C structs with SWIG
精彩评论