1
我試圖創建一個Game
實例,將它作爲變量game
傳遞到test.py的主名稱空間,然後調用game.add(e)
來運行C++函數,將實體e
添加到std :: vector中。但是,此代碼產生錯誤:使用C++中的方法創建實例並將其傳遞給Python
unbound method Boost.Python.function object must be called with Game instance as first argument (got Entity instance instead)
(一些背景:我試圖讓Python的創建將被保存在一個容器C++通過每一個刻度和更新運行情況下,我想我有它的工作在幾個星期前,但我回來吧,顯然它不工作 - 我知道,源代碼控制)
#include <vector>
class Entity{
public:
Entity(){}
Entity(float x, float y){}
};
class Game{
public:
Game();
void add(Entity* entity);
private:
std::vector<Entity*> objects_;
};
Game::Game(){
}
void Game::add(Entity* entity){
objects_.push_back(entity);
}
的main.cpp:
#include <iostream>
#include <boost/python.hpp>
#include "Game.h"
#include "Entity.h"
using namespace boost::python;
BOOST_PYTHON_MODULE(sfgame){
class_<Game>("Game")
.def("add", &Game::add)
;
class_<Entity>("Entity", init<float, float>())
;
}
int main(){
PyImport_AppendInittab("sfgame", &initsfgame);
Py_Initialize();
object main_module = import("__main__");
object main_namespace = main_module.attr("__dict__");
import("sfgame");
Game* game = new Game();
try{
main_namespace["game"] = ptr(game);
exec_file("test.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;
}
delete game;
system("PAUSE");
return 0;
}
test.py:
from sfgame import *
e = Entity(5,5)
game.add(e)