I had a working Pybind11 Module called maialib and I decided to split it in two files to get a better organization and reduce compile time.
To do that, I following this tutorial here:
https://pybind11.readthedocs.io/en/stable/faq.html#how-can-i-reduce-the-build-time
So, after that, my C++ code still compiles without any error! All ok!
Scanning dependencies of target maialib
[ 25%] Building CXX object CMakeFiles/maialib.dir/src/pugixml.cpp.o
[ 50%] Building CXX object CMakeFiles/maialib.dir/src/functions.cpp.o
[ 75%] Building CXX object CMakeFiles/maialib.dir/src/musicxml.cpp.o
[100%] Linking CXX shared module maialib.cpython-37m-darwin.so
[100%] Built target maialib
But when I tried to import maialib in the Python environment, I got this run-time error:
ImportError: dynamic module does not define module export function (PyInit_maialib)
Here is my CMakeLists.txt:
# Generate python module library
if(PYBIND_LIB)
message("=====> GENERATING PYBIND LIBRARY <=====")
add_definitions(-DPYBIND)
find_package(PythonLibs)
include_directories(${PYTHON_INCLUDE_DIRS})
add_subdirectory(pybind11)
pybind11_add_module(maialib src/pugixml.cpp src/functions.cpp src/musicxml.cpp)
target_include_directories(maialib PUBLIC include)
endif()
Here is my maialib.h:
// maialib.h
#include <pybind11/pybind11.h>
namespace py = pybind11;
void MusicXMLClass(py::module &);
void functions(py::module &);
PYBIND11_MODULE(maialib, m) {
m.doc() = "This is a Python binding of C++ Maia Library";
MusicXMLClass(m);
functions(m);
}
maialibHow can I fix this Python run-time error?
Same problem for me. I was following the tutorial for compiling with CMake.
I am using the latest version of Visual Studio 2017, which is 15.9.21. And Python 3.7.6 shipped with Anaconda.
Have you tried putting this code in a .cpp file instead of a header file?
PYBIND11_MODULE(maialib, m) {
m.doc() = "This is a Python binding of C++ Maia Library";
MusicXMLClass(m);
functions(m);
}
Perfect @carlsonmark !
The main PYBIND11_MODULE MUST BE inside a *.cpp file.
Now it works good!
Thank you again!
Most helpful comment
Have you tried putting this code in a .cpp file instead of a header file?