2016-01-02 26 views
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) 

回答

0

如果在主命名空間設置的變量名Game您會收到錯誤,因爲這將是一樣的類名。

但是,發佈的代碼是正確的。您必須編譯.pyd文件使用變量Game,意識到您的錯誤,然後將其更改爲game並編譯C++文件以測試它,而不重新編譯.pyd文件,以便錯誤仍然存​​在。

相關問題