我想从C++设置一个Python变量,以便C++程序可以创建一个对象Game* game = new Game();,以便Python代码能够引用这个实例(和调用函数等).我怎样才能做到这一点?
我觉得我对Python或Boost-Python的工作方式有一些核心的误解.
该行在main_module.attr("game") = gametry catch语句中,并且错误(使用PyErr_Fetch)是"为C++类型找到No to_python(by-value)转换器:class Game".
例如
class_<Game>("Game")
.def("add", &Game::add)
;
object main_module = import("__main__");
Game* game = new Game();
main_module.attr("game") = game; //This does not work
Run Code Online (Sandbox Code Playgroud)
来自Python:
import testmodule
testmodule.game.foo(7)
Run Code Online (Sandbox Code Playgroud) 我想将一个TestObj实例从C++代码传递给python.这里发布的代码在cout中产生错误:"为C++类型找不到to_python(by-value)转换器:class TestObj".如果我将对象创建移动main_module.attr("obj") = obj;到BOOST_PYTHON_MODULE宏中,代码运行正常.
当我尝试*TestObj使用或不使用boost :: ptr 时,会发生类似的事情.
testembed.py:
import sfgame
print("old x: " + str(obj.x))
obj.x = 10
print("new x: " + str(obj.x))
Run Code Online (Sandbox Code Playgroud)
testobj.h
class TestObj{
public:
TestObj();
int x;
int getX();
void setX(int xv);
};
Run Code Online (Sandbox Code Playgroud)
testobj.cpp
#include "TestObj.h"
TestObj::TestObj(){
}
int TestObj::getX(){
return x;
}
void TestObj::setX(int xv){
x = xv;
}
Run Code Online (Sandbox Code Playgroud)
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__"); …Run Code Online (Sandbox Code Playgroud)