[C++-sig] pyste generation of getitem/setitem .def's
Grant Goodyear
grant at grantgoodyear.org
Tue Nov 15 17:20:50 CET 2005
Okay, more searching of the archives brought me an answer. I'll attach
a complete, short, and silly example for the next person who runs into
this problem. My thanks to whomever provided the "Vector2d" example
from which I liberally stole.
-g2boojum-
--
Grant Goodyear
web: http://www.grantgoodyear.org
e-mail: grant at grantgoodyear.org
-------------- next part --------------
class Vector2d {
public:
Vector2d():x(0.0),y(0.0) {}
Vector2d(const double xval, const double yval): x(xval),y(yval) {}
~Vector2d() {}
double& operator[](const int i);
protected:
double x, y;
};
-------------- next part --------------
#include "foo.h"
double& Vector2d::operator[](const int i) { return i==0? x : y; }
-------------- next part --------------
#include "foo.h"
#include <boost/python.hpp>
#ifndef FOO_WRAP_H_
#define FOO_WRAP_H_
using boost::python::object;
object vec2dget(object self, object key);
void vec2dset(object self, object key, object val);
#endif // FOO_WRAP_H_
-------------- next part --------------
#include "foo_wrap.h"
#include "foo.h"
#ifndef FOO_H_
#define FOO_H_
using namespace boost::python;
object vec2dget(object self, object key) {
int i = extract<int>(key);
Vector2d& s = extract<Vector2d&>(self);
return object(s[i]);
}
void vec2dset(object self, object key, object val) {
Vector2d& s = extract<Vector2d&>(self);
int i = extract<int>(key);
double v = extract<double>(val);
s[i] = v;
}
#endif // FOO_H
-------------- next part --------------
Include("foo_wrap.h")
Vector2d = Class("Vector2d", "foo_wrap.h")
add_method(Vector2d, "vec2dget")
rename(Vector2d.vec2dget, "__getitem__")
add_method(Vector2d, "vec2dset")
rename(Vector2d.vec2dset, "__setitem__")
-------------- next part --------------
// Boost Includes ==============================================================
#include <boost/python.hpp>
#include <boost/cstdint.hpp>
// Includes ====================================================================
#include <foo_wrap.h>
// Using =======================================================================
using namespace boost::python;
// Module ======================================================================
BOOST_PYTHON_MODULE(libpyfoo)
{
class_< Vector2d >("Vector2d", init< >())
.def(init< const Vector2d& >())
.def(init< const double, const double >())
.def("__getitem__", &vec2dget)
.def("__setitem__", &vec2dset)
;
}
More information about the Cplusplus-sig
mailing list