【发布时间】:2017-02-12 20:36:29
【问题描述】:
我想使用 Pybind11 将一个简单的 C++ 函数集成到 Python 中。 考虑以下虚拟函数的简单示例:
#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();
}
我将此代码存储在名为 example.cpp 的函数中 我将 Python 3.5.2 与 Anaconda 一起使用。关注official documentation, 我编译脚本如下:
c++ -O3 -shared -std=c++11 -I /Users/SECSCL/anaconda3/include/python3.5m `python-config --cflags --ldflags` example.cpp -o example.so
我不确切知道“python-config”部分代表什么,但我知道它会导致问题。我尝试了三个选项:
- python-config:这会导致 clang 错误,链接器命令失败
- python3-config:与 python-config 相同的问题
-
python3.4-config:这实际上有效并创建了一个 example.so 文件。但是当我尝试从 python3.5 加载它时,我得到了错误
致命的 Python 错误:PyThreadState_Get:没有当前线程
总而言之,我的问题是:如何编译我的代码以便可以从 python3.5 加载它?或者更准确地说:我必须用什么来替换“python-config”语句?
【问题讨论】:
标签: c++ python-3.x pybind11