SWIG typemap to pass complex arrays into C++
Andrew Gregory
andrew.gregory at npl.co.uk
Fri May 31 05:40:45 EDT 2002
In a C++ header file (Borland BCC5.5) I have written
#include <complex.h>
typedef complex<double> dcomplex;
// Function to return i'th element of complex array
double getel (dcomplex *A, int i)
{ return real(A[i]); };
The function getel is illustrative only - not part of a real problem.
I have written a SWIG typemap to allow complex number arrays to be
passed:
%typemap(python,in) dcomplex *
{
if (!PyList_Check($input))
{
PyErr_SetString(PyExc_TypeError, "expected a list");
return NULL;
};
int arrsize = PyList_Size($input);
$1 = (dcomplex *)malloc(sizeof(dcomplex)*(arrsize+1));
for (int i=0; i<arrsize; i++)
{
PyObject *item = PyList_GetItem($input, i);
if (PyComplex_Check(item))
$1[i] = dcomplex(PyComplex_RealAsDouble(item),
PyComplex_ImagAsDouble(item));
else
{
free ((dcomplex *) $input);
PyErr_SetString(PyExc_TypeError, "expected complex numbers in
list");
return NULL;
};
}
}
%typemap (python,freearg) dcomplex *
{
free ((dcomplex *) $input);
};
SWIG (1.3.11u) runs ok. BCC5.5 compiles the wrapper file ok. But when
I try to use the function getel from Python 2.2.1 I get the error
message:
TypeError: Type error. Expected _p_dcomplex
I hand-coded my own wrapper and that worked, but can't make the
typemap work. Any suggestions?
Andrew.
More information about the Python-list
mailing list