python对象到本机c++poin

2024-04-26 23:35:12 发布

您现在位置:Python中文网/ 问答频道 /正文

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

这是我的课:

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";
    }
};

增强包装:

^{pr2}$

以及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的代码可以使用它。有什么想法吗?在


Tags: 对象alphareturndefvirtualextractpublicclass
3条回答

可能不是你正在寻找的答案,但是看看ChaiScript,以便嵌入到C++应用程序中。在

根据他们的网站

ChaiScript is the first and only scripting language designed from the ground up with C++ compatibility in mind. It is an ECMAScript-inspired, embedded functional-like language.

ChaiScript has no meta-compiler, no library dependencies, no build system requirements and no legacy baggage of any kind. At can work seamlessly with any C++ functions you expose to it. It does not have to be told explicitly about any type, it is function centric.

With ChaiScript you can literally begin scripting your application by adding three lines of code to your program and not modifying your build steps at all.

多亏了python c++邮件列表中的Stefan,我失踪了

super(Alpha, self).__init__()

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

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

现在很开心

嗯,我不确定它是否能帮到你,但是我在Lua中遇到了同样的问题。我们从Lua创建了对象,并需要一些c++代码通过指针来处理这些对象。我们做了以下工作:

  • 所有的对象都是用c++编写的,包括构造函数、析构函数和工厂方法
  • lua代码正在调用一个工厂方法来创建一个对象。这个工厂方法1)给对象一个唯一的ID号,2)在c++映射中注册它,将ID号映射到本机指针
  • 因此,每当lua要传递一个指向c++代码的指针时,它会给出一个对象ID,而c++代码则通过ID查找映射来查找实际的指针

相关问题 更多 >