I want to integrate a simple C++ function into Python using Pybind11. Consider the following simple example of a dummy function:
#include <vector>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
namespace py = pybind11;
// Dummy function: return a vector of size n, filled with 1
std::vector<int> generate_vector(unsigned int n)
{
std::vector<int> dummy_vector;
for(int i = 0; i < n; i++) dummy_vector.push_back(1);
return dummy_vector;
}
// Generate the python bindings for this C++ function
PYBIND11_PLUGIN(example) {
py::module m("example", "Generate vector of size n");
m.def("generate_vector", &generate_vector, "Function generates a vector of size n.");
return m.ptr();
}
I store this code in a function called example.cpp I use Python 3.5.2 with Anaconda. Following the official documentation, I compile the script follows:
c++ -O3 -shared -std=c++11 -I /Users/SECSCL/anaconda3/include/python3.5m `python-config --cflags --ldflags` example.cpp -o example.so
I do not know exactly what the 'python-config' part stands for, but I know it causes a problem. I have tried three options:
- python-config: This results in a clang error, linker command failed
- python3-config: Same problem as with python-config
python3.4-config: This actually works and creates an example.so file. But when I try to load it from python3.5, I obtain the error
Fatal Python error: PyThreadState_Get: no current thread
In summary, my question is: How do I compile my code so that I can load it from python3.5? Or more precisely: what do I have to replace the 'python-config' statement with?