【问题标题】:Extract class from python从python中提取类
【发布时间】:2011-03-22 17:07:05
【问题描述】:

我正在使用 boost.python 库作为脚本系统用 c++ 编写游戏。

我有一个抽象类Object。现在我创建新类,从Objects 继承它并写在某处Object *obj = new SomeCoolObject();

我还有一张对象地图:map<string, Object*> objects。所以在制作对象后我会这样做:objects.insert("name", obj);.

不要说释放内存等。我隐藏了那部分以减少代码(我正在使用智能指针)。

所以问题是:

我想要一个包含 python 文件的文件夹。在每个文件中,我描述了一些 Object 派生类,例如:

class SomeCoolObject(Object):
   ...

如何将该类绑定到 C++ 中?或者换句话说:如何在c++程序中说有这样的新类。

再一次:有一些带有此类类的 py 文件,我必须将它们全部导出。

有什么想法吗,伙计们?

【问题讨论】:

  • 换句话说:您从 C++ 基类派生 Python 类? Boost.Python 教程 (boost.org/doc/libs/1_46_0/libs/python/doc/tutorial/doc/html/…) 中描述了一种简单的方法,但它不会将 Python 类重新暴露给 C++。
  • @larsmans 我知道如何导出到 python。问题是如何从 python 导出新类型/类。
  • 您想自动将python类转换为C++类吗?为此,您需要 python->C++ 编译器。或者你想将python解释器加载到你的C++代码中并使用它来加载那个python类(它将继承自python中的Object,而不是你的C++代码)?你不能让 python 类直接从 C++ 类 (Object) 派生,中间没有任何东西

标签: c++ python class boost extract


【解决方案1】:

如果您已经加载了模块(例如,使用boost::python::import("module_name")),您应该能够通过attr() 成员函数引用其中的任何类。通常我会围绕它编写一个包装函数,因为如果类(或任何其他属性,就此而言)不存在,它会引发异常。例如:

boost::python::object getattr(const boost::python::object &obj, const std::string &name)
{
    try
    {
        return obj.attr(boost::python::str::str(name));

    }
    catch(const boost::python::error_already_set &err)
    {
        /* we need to fetch the error indicators *before*
         * importing anything, as apparently importing
         * using boost python clears the error flags.
         */

        PyObject *e, *v, *t;
        PyErr_Fetch(&e, &v, &t);

        boost::python::object AttributeError = boost::python::import("exceptions").attr("AttributeError");

        /* Squash the exception only if it's an AttributeError, otherwise
         * let the exception propagate.
         */
        if (PyErr_GivenExceptionMatches(AttributeError.ptr(), e))
            return boost::python::object(); // None

        else
            throw;
    }
}

[... later in the code ...]

using namespace boost::python;

object main_module = import("__main__");
object main_namespace = main_module.attr("__dict__");


object your_module = import("module_name");
object your_class = getattr(main_namespace, "SomeCoolObject");

// Now we can test if the class existed in the file
if (!your_class.is_none())
{
     // it exists! Have fun.
}

【讨论】:

    猜你喜欢
    • 2010-11-25
    • 2021-04-03
    • 1970-01-01
    • 2017-03-05
    • 2014-03-01
    • 2020-09-10
    • 2020-07-21
    • 2021-06-03
    • 2020-08-14
    相关资源
    最近更新 更多