Use Pyrex instead (Re: newbie at SWIG, help needed with typemaps)
Greg Ewing (using news.cis.dfn.de)
me at privacy.net
Mon Mar 31 00:40:25 EST 2003
Josh wrote:
> I hope this is not OT in this group. If it is, do let me know and I'll try
> my luck elsewhere.
Seems pretty much on-topic to me...
> 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.
Instead of SWIG, you might prefer to use Pyrex to wrap your C code:
http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/
This is exactly the sort of problem I designed Pyrex to solve.
The Pyrex code for it would look something like this (warning,
untested):
cdef extern void *malloc(int)
cdef extern void free(void *)
cdef extern void carr(double *, int)
def pycarr(int n):
cdef double *a
cdef int i
a = <double*>malloc(n * sizeof(double))
carr(a, n)
result = []
for i from 0 <= i < n:
result.append(a[i])
free(a)
return result
I hope you'll agree that this is a LOT saner than messing
about with SWIG!
(A minor problem is that you can't currently call the
Python function "carr" or it will conflict with the
C one. That will be fixed in a later release...)
--
Greg Ewing, Computer Science Dept,
University of Canterbury,
Christchurch, New Zealand
http://www.cosc.canterbury.ac.nz/~greg
More information about the Python-list
mailing list