I want to pass an instance of TestObj from the C++ code into python. The code posted here produces the error in cout: "No to_python (by-value) converter found for C++ type: class TestObj". If I move the object creation and main_module.attr("obj") = obj;
into the BOOST_PYTHON_MODULE macro, the code runs fine.
Similar things happen when I try passing a *TestObj
with or without boost::ptr.
testembed.py:
import sfgame
print("old x: " + str(obj.x))
obj.x = 10
print("new x: " + str(obj.x))
testobj.h
class TestObj{
public:
TestObj();
int x;
int getX();
void setX(int xv);
};
testobj.cpp
#include "TestObj.h"
TestObj::TestObj(){
}
int TestObj::getX(){
return x;
}
void TestObj::setX(int xv){
x = xv;
}
main.cpp
#include <boost/python.hpp>
#include "TestObj.h"
using namespace boost::python;
BOOST_PYTHON_MODULE(sfgame){
class_<TestObj>("TestObj")
.add_property("x", &TestObj::getX, &TestObj::setX)
;
}
int main(){
Py_Initialize();
object main_module = import("__main__");
object main_namespace = main_module.attr("__dict__");
TestObj obj;
try{
obj.setX(5);
main_module.attr("obj") = obj;
exec_file("testembed.py", main_namespace);
}
catch (const boost::python::error_already_set &){
PyObject *ptype, *pvalue, *ptraceback;
PyErr_Fetch(&ptype, &pvalue, &ptraceback);
std::string error;
error = boost::python::extract<std::string>(pvalue);
std::cout << error << std::endl;
}
system("PAUSE");
return 0;
}