[SciPy-user] FYI: C++ Extensions for Python
John Hunter
jdhunter at ace.bsd.uchicago.edu
Mon Nov 1 22:14:49 EST 2004
>>>>> "David" == David Grant <david.grant at telus.net> writes:
David> pycxx - Looks like it requires one to modify all the C++
David> source, adding PyObject pointers everywhere. I stayed away
David> from this. I don't want to modify the code if I have to
David> (why should I have to? the reason I'm making an interface
David> is so that I can use the C++ code, and not touch it, thus
David> avoiding creating bugs in the C++ code. If I WANTED to
David> touch the C++ code I'd just re-write in python).
Not at all. Typically, you do not modify any of the C++ code in the
library you are wrapping; I never have.
Suppose you are wrapping a C++ function that takes a pointer to x
and a pointer to y and returns void, using the pointers as the return
value. Suppose x and y aren't used in calculating the return, but are
merely used to handle the return value.
void SomeClass::somefunc(double *x, double *y);
In python you would typically want to do
x, y = o.somefunc()
In pycxx, you would include the header that defines the class that
somefunc lives in, and wrap it like
Py::Object
SomeClassPy::somefunc(const Py::Tuple & args) {
args.verify_length(0);
double x(0),y(0);
_p->somefunc(&x, &y);
Py::Tuple xy(2);
xy[0] = Py::Float(x);
xy[1] = Py::Float(y);
return xy;
}
Here _p is a pointer to a SomeClass instance. Your wrapper class
SomeClassPy wraps SomeClass -- you do not alter SomeClass in any way.
True, it requires some additional boilerplate to hand wrap the
function. I like it because 1) it gives you total control on how to
process the input and output args, 2) allows you to write pythonic c++
with Py::Tuple, Py::Dict, Py::Float, etc. 3) handles all the reference
counting 4) supports all the special methods for emulating numeric
types, comparisons, mapping/seq types etc.
Other wrapping libraries do more to automate the process of wrapping.
But can any of them handle changing around the input and output args
as above to make the interface more pythonic, w/o having to write some
dedicated wrapper code. Ie, in pyfort I believe you can declare
arguments as input or output and the wrapper will rearrange everything
for you. Do any of the C++ wrapper generators support this?
JDH
More information about the SciPy-User
mailing list