I git clone
d pybind11's cmake exmaple. Then I built it with pip install ./cmake_example
. My python file contains the following:
import cmake_example
print(cmake_example.add(1, 2))
This works fine. Now I want to use pybind11
's interpreter. I changed the CMakeLists.txt
according to the instructions in the docs. Below are what I have now:
main.cpp
#include <pybind11/embed.h>
namespace py = pybind11;
int main()
{
py::scoped_interpreter guard{};
py::print("Hello world");
}
PYBIND11_MODULE(cmake_example, m)
{
m.def("main", &main);
}
CMakeLists.txt
cmake_minimum_required(VERSION 2.8.12)
project(cmake_example)
add_subdirectory(pybind11)
add_executable(cmake_example src/main.cpp)
target_link_libraries(cmake_example PRIVATE pybind11::embed)
example.py
import cmake_example
cmake_example.main()
When I run the above python file, I get the following error:
Traceback (most recent call last): File "example.py", line 2, in cmake_example.main() AttributeError: module 'cmake_example' has no attribute 'main'
What am I doing wrong?
I think you are mixing two different approaches up.
Embedding specifically refers to embed the python interpreter into an existing executable. The document that you refer to make it (or try to) quite clear.
What it means is that you should have a C/C++ executable from which you can execute python code (either inside a file or as a string).
Now that this is out of the way, look inside your built directory and you will find a cmake_example binary. Run it and you will see the print. You cannot directly import this built module from within standard python interpreter, rather it is available inside the file invoked from the custom executable, cmake_example in this case.
You can also run example.py by changing the code as following:
int main()
{
py::scoped_interpreter guard{};
py::eval_file("example.py");
}