Passing complex numbers into C++
Andrew Gregory
andrew.gregory at npl.co.uk
Mon May 27 12:28:45 EDT 2002
I am trying to produce a bit of code to illustrate how complex numbers
can be passed to / from C++ (BCC5.5). I'm new to this, and finding it
hard going. The following bit of code compiles to complx.pyd - which
imports into python ok, but if I use the csqr() function it causes a
crash. If anyone can tell me why I would be grateful,
Andrew.
/ Example hand-coded C++ interface to Python
#include <Python.h>
#include <complex.h>
typedef complex<double> dcomplex;
// **** Function (illustrative) ****
Py_complex csqr(Py_complex r)
{
static Py_complex P;
dcomplex t = dcomplex(r.real, r.imag);
t = t*t;
P.real = real(t);
P.imag = imag(t);
return P;
};
// **** Wrapper ****
PyObject *wrap_csqr(PyObject *self, PyObject *args)
{
Py_complex r, result;
// r = new Py_complex;
if (!PyArg_ParseTuple(args,"D:csqr", &r)) return NULL;
//result = r;
return Py_BuildValue("D",&r);
};
static PyMethodDef exampleMethods[] =
{
{ "csqr", wrap_csqr, 1 }, {NULL, NULL}
};
// Must use this for C++
#ifdef __cplusplus
extern "C" {
#endif
void initcomplx()
{
PyObject *m;
m = Py_InitModule("complx",exampleMethods);
};
#ifdef __cplusplus
}
#endif
More information about the Python-list
mailing list