Boost Python Conceptual Problem
Posted: Mon Apr 02, 2012 3:44 pm
I'm having a conceptual issue with the way C++ interfaces with Python (boost::python). I'm trying to convert a C++ object to a Python object, but my attempt causes the program to crash. I think 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.
Code: Select all
#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());
}
};
/**** In the lib ****/
// I believe this bit is only used if you create the object in Python
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;
}