SWIG, Ruby, C and typemaps

Hello all. I am seeking some advice on using SWIG to wrap some native
C code provided to me (I don’t have the ability to change it).
Basically, I have something like this:

The definition of one of the problematic methods I am trying to wrap
looks something like this. This is in my SWIG interface file (.i
file):

int open_file(ResponseObject **resp, const char *fname);

And the normal way of using this is as follows:

ResponseObject *reponsObj;
const char *filename=“input_file”;

if(open_file(&reponsObj, filename)!=0)
{
// handle non-zero error code
}
else
{
// success!
}

I think the most natural way of accessing this method might be
something like this:

resp = open_file(‘input_file’)

In this scenario, resp is a Ruby object representing ResponseObject,
and the original int return value is now mapped to a conditionally
thrown exception. If open_file returns 0, then no exception would be
thrown, otherwise, the Ruby method open_file would throw an exception
which wraps the int return code.

Thoughts? I know there is some SWIG/typemap magic that can do this,
but so far I’m a bit stumped. Can someone offer some advice? I can
provide more details if needed.

Thanks so much in advance for your help. Much appreciated.

-Jeff

Jeff Sack wrote:

The definition of one of the problematic methods I am trying to wrap
looks something like this. This is in my SWIG interface file (.i
file):

int open_file(ResponseObject **resp, const char *fname);

I think the most natural way of accessing this method might be
something like this:

resp = open_file(‘input_file’)

You’lll first want a typemap to tell SWIG to convert one ruby input (the
string filename) into the two parameters C is expecting. Along the lines
of (untested)

%typemap(in,numinputs=1) (ResponseObject **resp, const char *fname) {
$1 = new ResponseObject();
$2 = rb_str_new2(fname);
}

Then you’ll need another typemap to treat the resp argument as a ruby
return value, and convert it to a ruby wrapper round the C object.

%typemap(argout) (ResponseObject **resp) {
$result = SWIG_NewPointerObj($1, $1_descriptor, 1);
}

hth
alex

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs