Ruby callback for a SWIG wrapped C function

Hello list!

I successfully wrapped using swig a library I wrote in ruby, all its
simple
functions works very well.
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!

By the way, may I meet problems if some of my functions uses the
“callback-needing” function inside of them?

Than kyou

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:

  1. 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
file.

%{
void DoYielding(int arg_1)
{
VALUE rb_arg_1 = INT2NUM(arg_1);
rb_yield(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.

  1. 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);
C_Function_Needing_Callback(input_arg, &DoYielding);
return Qnil;
}

Then do whatever you need to get this function mapped to a ruby method,
using normal SWIG techniques.

  1. 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
end

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++.

a

On Wed, Aug 20, 2008 at 12:06 PM, Alex F.
[email protected]wrote:

rb_yield(arg_1);
the method that is exposed in ruby will look something like

Not if you do it right. You can still call the callback-needing function
with a normal callback, written in pure C/C++.

a

Thank tou for the Reply, I’ll try what you suggested me. If I have more
troubles, I will repost another message