I have a C++/Pybind11 function that receives a Python package foo
as argument.
My package is just a directory named ‘foo’ with two files in it:
foo
+ __init__.py
+ bar.py
The bar.py
just contains some variables, such as test. In the C++ function I need to access the module bar
within that package.
From Python this is easily done with from foo import bar
and in fact this works correctly as I tested it using the following Python code):
from foo import bar
print(bar.test)
This works correctly. I read that in Pybind11 to access a module within a package I should use the attr
method but this doesn’t seem to work as I always get an error
saying that the bar
attribute does not exist. This is the C++ code:
void Engine::start(py::module& foo) {
try {
py::module settings = foo.attr("bar");
std::cout << "okn";
} catch (py::error_already_set& e) {
std::cout << "errorn";
PyErr_Print();
}
Needless to say, ok is never printed and I always end up in the error branch. Now my question is: is there a way to access a module within a package from C++? If so, how should it be done?