Error extending and embedding Python 3.5 with pybind11

1k Views Asked by At

I'm starting to play with the library pybind11. It's really good library, well documented and it works for me but only with Python 2.7. I'm not able to get it working for Python 3.5 and I don't know what I'm doing wrong.

This is my "hello world" program:

#include <pybind11/pybind11.h>
namespace py = pybind11;

const char * world() { return "Hello world!"; }

int main(int argc, char ** argv) {

    Py_Initialize();

    py::module m("hello", "my hello world Python module with pybind11");
    m.def("world", &world);

    PyRun_SimpleString("import hello\nprint( hello.world() )");

    Py_Finalize();

    return 0;
}

If I compile and link against 2.7, I get the expected result:

Hello world!

But if I link exactly the same code with Python 3.5, I get an error loading the module.

Traceback (most recent call last):
  File "<string>", line 1, in <module>
ImportError: No module named 'hello'

Any ideas?

1

There are 1 best solutions below

0
On

How did you compile the library and what system are you on? If you used python-config as suggested in the basic example in their documentation (the command below), you'll compile against the development version on your machine.

 c++ -O3 -shared -std=c++11 -I <path-to-pybind11>/include `python-config --cflags --ldflags` example.cpp -o example.so

This is likely Python 2.7 even if you use Python 3.5. In my case, I used Anaconda to install python, and that gave me Python 3.5, but the system Python is still 2.7.

What does python-config give you? Is the version listed Python 3.5? If it is not you cannot use this command at least without modifications. What you can do is cmake build system as described in their documentation. That fixed it for me. Using their setuptools system, would probably also work. Basically, they figure out what you used to compile their library and use those flags. This does mean, that you have to make sure that you are linking against Python 3.5 when building the library itself.