[C++-sig] Boost::Python to_python converter
DarkAnt
darkant at gmail.com
Tue Apr 3 17:01:33 CEST 2012
I'm having a conceptual issue with the way C++ interfaces with Python.
I'm trying to convert a C++ object to a Python object, but my attempt
causes the program to crash. I suspect I'm doing a lot of things
wrong. Ultimately I'd like to be able to pass C++ objects to a python
function that modifies their values.
#include <boost/python.hpp>
#include <string>
struct Unit
{
int health;
std::string name;
std::string type;
std::pair<int,int> coord;
};
struct Unit_to_python
{
static PyObject* convert(Unit const& unit)
{
return boost::python::incref(boost::python::object(unit).ptr());
}
};
BOOST_PYTHON_MODULE(game)
{
boost::python::class_<Unit>("Unit")
.def_readwrite("health", &Unit::health)
.def_readwrite("name", &Unit::name)
.def_readwrite("type", &Unit::type)
.def_readwrite("coord", &Unit::coord)
;
}
int main(int argc, char** argv)
{
Py_Initialize();
boost::python::to_python_converter<Unit, Unit_to_python>();
Unit unit1;
unit1.health = 100;
unit1.name = "Tank";
unit1.type = "Armor";
boost::python::object foo(unit1); // crash: stack overflow
return 0;
}
More information about the Cplusplus-sig
mailing list