Lyes A. wrote:
I said simple because I have a function that takes a callback function as
argument, and I look for the way how to give a pure ruby callback function
as argument of this function wrapped by SWIG
You haven’t supplied enough detail to provide specific advice so you’ll
need to adapt what follows. A generally effective way of dealing with
this is in SWIG to do something like:
- Create a short ‘bridging’ function in C that converts arguments to
ruby and then calls rb_yield
Let’s say your callback function is expected to take a single int
argument and returns void. Put this is in as a SWIG literal in your .i
void DoYielding(int arg_1)
VALUE rb_arg_1 = INT2NUM(arg_1);
If the callback needs to return a value, you’ll need to capture the
return value of rb_yield and do some Ruby -> C type translation.
- Set it up so that method calls in ruby to the original
callback-needing function supply this callback as the C argument
If the callback-needing function needs to accept a single int parameter,
the method that is exposed in ruby will look something like
VALUE method_needing_callback(VALUE rb_input_arg)
int input_arg = NUM2INT(rb_input_arg);
Then do whatever you need to get this function mapped to a ruby method,
using normal SWIG techniques.
- Compile, and call the method with a block
some_object.method_needing_callback(42) do | an_int |
puts “The callback was called with argument %i” % an_int
By the way, may I meet problems if some of my functions uses the
“callback-needing” function inside of them?
Not if you do it right. You can still call the callback-needing function
with a normal callback, written in pure C/C++.