From: Tobias Peters Date: 2004-11-21T22:58:07+09:00 Subject: Re: SWIG and Arrays (of ints) Kurt Dresner wrote: > Hi all, > > I'm trying to get SWIG to create a wrapper for some C code. > Specifically, there are several functions that take, as parameters, an > int* (they also take the length of the array). I don't know how to do > the typemap for this - I want to be able to write > > My_module.my_c_function([1,2,3]) > > for the corresponding C function > > void my_c_function(int size, int* ary) > > Additionally, one of the functions takes an integer array as a > parameter, and I'd like it instead to return an array in Ruby (full of > Nums). I know how to get it to return the argument (instead of doing > the pointer passing thing), but then it just thinks I want to pass it > an integer instead of an array of integers. > > Anyone have any idea how to help me? Everything I've seen pertains to > char** and I'm not sure how to convert it to work how I want with > int*. Passing an array of integers from Ruby to C with SWIG requires multi-argument "in" and "freearg" typemaps: %typemap(ruby,in) (int size, int *ary) { int i; if (!rb_obj_is_kind_of($input,rb_cArray)) rb_raise(rb_eArgError, "Expected Array of Integers"); $1 = RARRAY($input)->len; $2 = malloc($1*sizeof(int)); for (i=0; i<$1; ++i) ($2)[i] = NUM2INT(RARRAY($input)->ptr[i]); } %typemap(freearg) (int size, int *ary) { if ($2) free($2); } There's room for improvement in handling (or better: preventing) exceptions raised from NUM2INT (proper error message and deallocation of C array). Regarding output: It's not clear to me if you want in/out semantics or output only. I think you can achieve in/out with an additional multi-argument "argout" typemap. Output only implementation depends on which function is responsible for allocating/freeing the array and which is responsible for determining the array's size. You may need an additional "arginit" typemap for this one. Tobias