在pybind11的嵌入式C++程序中,我定义了一个python模块,用作多个python对象的容器,我不想将这些对象公开给全局名称空间。然后,我想根据需要导入此模块。但是看起来仅仅通过py::module('mymodule')定义一个模块是不够的。
下面的示例代码编译时没有问题,但在运行时出现错误"No module named 'application'“而终止。那么如何让"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)");
}发布于 2019-10-08 22:35:34
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);
}https://stackoverflow.com/questions/58283261
复制相似问题