python - 使用 C++ 中的方法创建实例并将其传递给 Python

标签 python c++ boost boost-python

我正在尝试创建 Game 的实例,将其作为变量 game 传递到 test.py 的主命名空间,然后调用 game .add(e) 以运行将实体 e 添加到 std::vector 中的 C++ 函数。但是,此代码会产生错误:

未绑定(bind)方法 Boost.Python.function 对象必须以 Game 实例作为第一个参数调用(取而代之的是 Entity 实例)

(一些上下文:我试图让 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);
}

主要.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;
}

测试.py:

from sfgame import *

e = Entity(5,5)
game.add(e)

最佳答案

如果您将主命名空间中的变量名设置为 Game,您将收到该错误,因为它与类名相同。

但是,发布的代码是正确的。您必须使用变量 Game 编译 .pyd 文件,意识到您的错误,然后将其更改为 game 并编译 C++ 文件以测试它,而无需重新编译 .pyd 文件所以错误仍然存​​在。

关于python - 使用 C++ 中的方法创建实例并将其传递给 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34570557/

相关文章:

c++ - 最大命令行参数

c++ - 为什么这个用于计算最长公共(public)子序列的并行函数比串行函数慢?

c++ - 检查真值上下文中的空指针

c++ - 在 Release模式下 boost 线程崩溃

python - 如何从 Python 的集合库中查看 deque 模块的源代码?

python - 反规范化单位向量

python - 如何使用 Python 从 zip 文件中去除密码加密

c++ - Boost named_mutex 无法在不同用户创建的进程之间共享

c++ - 使用 Boost Interprocess 1.60 发布版本时出现奇怪的链接器错误

python - 数组与稀疏矩阵的相关性