使用python3配置的Pybind11编译不起作用

Pybind11 compilation with python3-config not working

本文关键字:编译 不起作用 Pybind11 python3 配置 使用      更新时间:2023-10-16

我想使用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一起使用。根据官方文件,我编译脚本如下:

c++ -O3 -shared -std=c++11 -I /Users/SECSCL/anaconda3/include/python3.5m `python-config --cflags --ldflags` example.cpp -o example.so

我不知道"python config"部分到底代表什么,但我知道它会引起问题。我试过三种选择:

  1. python配置:这导致clang错误,链接器命令失败
  2. python3配置:与python配置相同的问题
  3. python3.4-config:这确实有效,并创建了一个example.so文件。但当我试图从python3.5加载它时,我得到了错误

    Python致命错误:PyThreadState_Get:没有当前线程

总之,我的问题是:如何编译我的代码,以便从python3.5加载它?或者更准确地说:我必须用什么来替换"python config"语句?

我能够在我的macOS Sierra 2015年初的MacBook Pro上运行您的示例。

我使用了您的example.cxx代码,没有任何更改。

在编译模块之前,必须确保anaconda环境处于活动状态,以便编译命令调用正确的python-config命令。

在我的例子中,这是用:source ~/miniconda3/bin/activate完成的——显然必须用anaconda3替换miniconda3

现在仔细检查您的compile命令是否会通过执行以下操作来调用正确的python-configwhich python3.5-config——这应该表明它正在使用您的anaconda3python3.5-config

现在您可以如下调用编译:

c++ -O3 -shared -std=c++11 -I $HOME/build/pybind11/include 
-I $HOME/miniconda3/include/python3.5m 
`python3.5m-config --cflags --libs` -L $HOME/miniconda3/lib/ 
example.cpp -o example.so

注意,我必须将include路径添加到我的pybind11签出中,指定确切的python-config版本(3.5m),将--ldflags更改为--libs,这样python-config就不会添加会导致错误的--stack-size链接参数,最后,我为包含libpython3.5m.dylib的miniconda3(在您的情况下是anaconda)目录添加了-L

在这之后,我可以做:

$ python
Python 3.5.2 |Continuum Analytics, Inc.| (default, Jul  2 2016, 17:52:12)
[GCC 4.2.1 Compatible Apple LLVM 4.2 (clang-425.0.28)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import example
>>> v = example.generate_vector(64)
>>> print(v)
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

非常整洁!