嵌入式Python:从导入的模块获取func obj
Embedded Python: Getting func obj from imported module
我有一个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.create
和getattr(hero, 'create')
是一样的。
您也可以直接使用boost::python::import
,而不是使用exec
import语句。
相关文章:
- 获取 LLVM 模块中的所有值
- 无法在 XmlHttpRequest 模块上获取断点(Javascript 引擎/XHR 请求)
- 使用 libunwind 获取模块地址
- 获取模块文件名 Win 7/Win 10 上的不同行为
- 哪种方法更好获取静态链接DLL的模块句柄(HMODULE) - 使用GetModuleHandleEx()或LoadLibrary()?
- 使用 Module32First 获取模块的 modBaseAddr 不返回任何内容
- 如何使用getForegroundWindow函数获取模块
- 获取 .NET 模块的图像大小
- Apache模块-获取请求正文
- 获取传递给子模块(C#.NET dll)中的主模块(VC++ exe)的参数
- 在C++中获取 Linux 内核模块的详细信息
- 获取模块文件名不返回路径
- 从节点.js模块获取 D9025 警告和 C1083 错误...我没主意了
- 如何在64位应用程序中获取模块大小
- 如何获取当前运行模块的sc_module_name
- 从其他进程获取模块句柄
- 嵌入式Python - [_socket获取模块方法,但socket.py:缺少方法]
- 从另一个模块获取派生类指针的接口
- 获取模块大小
- 嵌入式Python:从导入的模块获取func obj