【发布时间】:2015-11-28 15:58:34
【问题描述】:
我想将 C++ 代码中的 TestObj 实例传递给 python。此处发布的代码在 cout 中产生错误:“No to_python (by-value) converter found for C++ type: class TestObj”。如果我将对象创建和main_module.attr("obj") = obj; 移动到 BOOST_PYTHON_MODULE 宏中,代码运行良好。
当我尝试在有或没有 boost::ptr 的情况下传递 *TestObj 时,也会发生类似的事情。
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;
}
【问题讨论】:
标签: python c++ boost boost-python