gpt4 book ai didi

c++ - 使用 python3-config 进行 Pybind11 编译不起作用

转载 作者:行者123 更新时间:2023-12-03 07:26:04 25 4
gpt4 key购买 nike

我想使用 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”语句?

    最佳答案

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

    我用了你的example.cxx代码没有任何变化。

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

    就我而言,这是通过以下方式完成的:source ~/miniconda3/bin/activate -- 你显然必须替换 miniconda3anaconda3 .

    现在仔细检查您的编译命令是否会调用正确的 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会导致错误的链接参数,最后我添加了一个 -L对于包含 libpython3.5m.dylib 的 miniconda3(在您的情况下为 anaconda)目录

    在此之后,我可以这样做:
    $ 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]

    ......这很整洁!

    关于c++ - 使用 python3-config 进行 Pybind11 编译不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42023817/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com