【问题标题】:Pybind11 compilation with python3-config not working使用 python3-config 进行 Pybind11 编译不起作用
【发布时间】: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”部分代表什么,但我知道它会导致问题。我尝试了三个选项:

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

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

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

【问题讨论】:

    标签: c++ python-3.x pybind11


    【解决方案1】:

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

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

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

    在我的例子中,这是通过 source ~/miniconda3/bin/activate 完成的——你显然必须将 miniconda3 替换为 anaconda3

    现在仔细检查您的编译命令是否会调用正确的python-config,方法是:which python3.5-config——这应该表明它正在使用您的 anaconda3 python3.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
    

    请注意,我必须将包含路径添加到我的 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]
    

    ...非常整洁!

    【讨论】:

    • 谢谢!这解决了我的问题。我遇到了 python - config 配置问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-15
    • 1970-01-01
    • 2019-07-21
    • 2021-06-11
    相关资源
    最近更新 更多