在pybind11中的嵌入式C ++程序中,我定义了一个python模块,用作多个我不想公开给全局命名空间的python对象的容器。然后,我想根据需要导入该模块。但是看来仅通过py::module('mymodule')
定义模块是不够的。
以下示例代码可以毫无问题地进行编译,但是会以运行时错误“ No module named'application'”终止。那么如何使python知道“应用程序”模块呢?
#include <pybind11/embed.h>
namespace py = pybind11;
int main(int argc, char *argv[])
{
py::scoped_interpreter guard{};
// Construct python wrappers for them
py::module m("application");
// Define some objects in the module
m.add_object("pet", py::cast("dog"));
// Import the module and access its objects
py::exec("import application\n"
"print(application.pet)");
}
答案 0 :(得分:0)
Pybind定义了PYBIND11_EMBEDDED_MODULE
宏来创建嵌入式模块。
https://pybind11.readthedocs.io/en/stable/advanced/embedding.html#adding-embedded-modules
#include <pybind11/embed.h>
namespace py = pybind11;
PYBIND11_EMBEDDED_MODULE(fast_calc, m) {
// `m` is a `py::module` which is used to bind functions and classes
m.def("add", [](int i, int j) {
return i + j;
});
}
int main() {
py::scoped_interpreter guard{};
auto fast_calc = py::module::import("fast_calc");
auto result = fast_calc.attr("add")(1, 2).cast<int>();
assert(result == 3);
}