嵌入式Python:从导入的模块获取func obj

Embedded Python: Getting func obj from imported module

本文关键字:模块 获取 func obj 导入 Python 嵌入式      更新时间:2023-10-16

我有一个Python模块,我从我的c++代码导入(我嵌入Python)。这个模块包含一个函数create(),我想在我的c++代码中获得一个控制(即将其存储在boost::python::object实例中)。

这是我试过的。在我的c++代码的指定行上出现运行时错误。出现错误是因为无法找到"英雄"。

c++代码

namespace python = boost::python;
// Standard Boost.Python code
// Here I just create objects for the main module and its namespace
python::object main_module(
    python::handle<>(python::borrowed(PyImport_AddModule("__main__")))
);
python::object main_namespace(main_module.attr("__dict__"));

// This is my code
//
python::exec("import hero", main_namespace, main_namespace);
python::object func(main_namespace["hero.create"]); // Run-time error
Entity ent = python::extract<Entity>(func());
// I also tried doing this, but it didn't work either...
// python::object func(main_namespace["hero"].attr("__dict__")["create"]);
// However, if I do this, all works fine...
// python::exec("from hero import create", main_namespace, main_namespace);
// python::object func(main_namespace["create"]); // No error

Python代码( hero.py )

from entity import Entity
def create():
    ent = Entity()
    # ...
    return ent

你需要做main_namespace["hero"].attr("create")。Import只在命名空间中创建一个名称,它是一个模块对象。名称中不能有点——.是一个getattr运算符——所以hero.creategetattr(hero, 'create')是一样的。

您也可以直接使用boost::python::import,而不是使用exec import语句。