newbie at SWIG, help needed with typemaps

Josh mlsj at earthlink.net
Sun Mar 30 18:45:59 CEST 2003


I hope this is not OT in this group. If it is, do let me know and I'll try 
my luck elsewhere. I have a simple C function. When called from a C 
program, void carr is handed a properly malloc'ed double pointer and an int 
len. carr then proceeds to fill up the first len locations of the double 
array represented by double *sd. When called from python, I just want to 
pass the len as in (in module trl) trl.carr(len). In that case, the wrapped 
C function should then proceed to dynamically allocate the double array, 
fill it up, convert it to a Python object, and return a list of  len 
elements. Does that make sense? I have been trying to fool around with 
%typemaps, %inline, %rename and everything else for the last two days and 
getting nowhere. 

The C function is:

void carr(int len,double *sd)
{
   int i=0;
   
   for(i=0;i<len;i++){
	   *sd++=i*0.2334;
   }
   sd-=len-1;
   }

What I want is :

s=trl.carr(len)
s=list of double values(or Python float)

Here is the interface file that comes closest to what I want to do .However 
this necessitates me fooling around with the wrap_carr(..) function to get 
the behavior I want. Can somebody help? And if this is OT, please point me 
in the right direction.

%module trl

%rename(carr) wrap_carr;
%typemap(in)int len(double *d){
$1=PyInt_AsLong($input);
arg2=(double *)malloc($1*sizeof(double));

}


%typemap(argout) (double *OutValue) {
int i;
PyObject *o;
PyObject *d;
o=PyList_New($1);
for(i=0;i<$1;i++)
{
d=PyFloat_FromDouble(arg2[i]);
PyList_Append(o, d);
}
$result=o;

}




More information about the Python-list mailing list