c++ - python 对象到 native c++ 指针

标签 c++ python boost embedded-language

我正在考虑使用 python 作为我正在从事的项目的嵌入式脚本语言,并且已经完成了大部分工作。但是我似乎无法将 python 扩展对象转换回 native c++ 指针。

这就是我的类(class):

class CGEGameModeBase
{
public:
    virtual void FunctionCall()=0;
    virtual const char* StringReturn()=0;
};

class CGEPYGameMode : public CGEGameModeBase, public boost::python::wrapper<CGEPYGameMode>
{
public:
    virtual void FunctionCall()
    {
        if (override f = this->get_override("FunctionCall"))
            f();
    }

    virtual const char* StringReturn()
    {
        if (override f = this->get_override("StringReturn"))
            return f();

        return "FAILED TO CALL";
    }
};

boost 包装:

BOOST_PYTHON_MODULE(GEGameMode)
{
    class_<CGEGameModeBase, boost::noncopyable>("CGEGameModeBase", no_init);

    class_<CGEPYGameMode, bases<CGEGameModeBase> >("CGEPYGameMode", no_init)
        .def("FunctionCall", &CGEPYGameMode::FunctionCall)
        .def("StringReturn", &CGEPYGameMode::StringReturn);
}

和Python代码:

import GEGameMode

def Ident():
    return "Alpha"

def NewGamePlay():
    return "NewAlpha"


def NewAlpha():
    import GEGameMode
    import GEUtil

    class Alpha(GEGameMode.CGEPYGameMode):
        def __init__(self):
            print "Made new Alpha!"

        def FunctionCall(self):
            GEUtil.Msg("This is function test Alpha!")

        def StringReturn(self):
            return "This is return test Alpha!"

    return Alpha()

现在我可以通过这样做来调用第一个函数:

const char* ident = extract< const char* >( GetLocalDict()["Ident"]() );
const char* newgameplay = extract< const char* >( GetLocalDict()["NewGamePlay"]() );

printf("Loading Script: %s\n", ident);
CGEPYGameMode* m_pGameMode = extract< CGEPYGameMode* >( GetLocalDict()[newgameplay]() );

但是,当我尝试将 Alpha 类转换回其基类(上面最后一行)时,我收到一个 boost 错误:

TypeError: No registered converter was able to extract a C++ pointer to type class CGEPYGameMode from this Python object of type Alpha

我在网上进行了大量搜索,但无法弄清楚如何将 Alpha 对象转换为其基类指针。我可以将它保留为对象,而是将其作为指针,以便一些非 Python 感知的代码可以使用它。有什么想法吗?

最佳答案

感谢 python c++ 邮件列表中的 Stefan,我失踪了

super(Alpha, self).__init__()

来自构造函数调用,这意味着它从未创建父类。以为这会是自动的:D

我遇到的唯一问题是将新的类实例保存为全局变量,否则它会在超出范围时被清理。

现在很开心

关于c++ - python 对象到 native c++ 指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1355187/

相关文章:

c++ - 使用宏获取函数参数 'name'

c++ - 客户端 gRPC 连接在 C++ 中重新连接?

c++ - glReadPixels 存储 x, y 值

c++ - 将 int 元组转换为 int 并返回

python - 在双索引 Groupby Dataframe 中查找最小值的内部索引

c++ - 函数拒绝在 Boost 测试函数中工作

c++ - Boost String Replace 不会用字符串替换换行符

c++ - boost::asio 读/写问题

python - Flask - 'NoneType' 对象不可调用

python - 写入并发日志文件