首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >python3 3-config不起作用的Pybind11编译

python3 3-config不起作用的Pybind11编译
EN

Stack Overflow用户
提问于 2017-02-03 12:00:35
回答 1查看 1.6K关注 0票数 1

我希望使用C++将一个简单的Pybind11函数集成到Python中。考虑以下虚拟函数的简单示例:

代码语言:javascript
复制
#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的函数中,我在Anaconda中使用Python3.5.2。在正式文件之后,我编译脚本如下:

代码语言:javascript
复制
c++ -O3 -shared -std=c++11 -I /Users/SECSCL/anaconda3/include/python3.5m `python-config --cflags --ldflags` example.cpp -o example.so

我不知道“”部分到底代表什么,但我知道它会导致问题。我尝试了三种选择:

  1. python-config:这将导致clang错误,链接器命令失败。
  2. python3-config:与相同的问题
  3. python3.4-config:这实际上可以工作,并创建一个example.so文件。但是当我试图从python3.5加载它时,我得到了错误 致命Python错误: PyThreadState_Get:没有当前线程

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-02-12 12:36:29

我能够让你的例子在我的macOS塞拉利昂2015年初的MacBook Pro。

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

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

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

现在,再次检查编译命令是否将调用正确的python-config,方法是:which python3.5-config --这应该表明它正在使用anaconda3 python3.5-config

现在,您可以按以下方式调用编译:

代码语言:javascript
复制
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

在这之后,我可以:

代码语言:javascript
复制
$ 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]

..。挺不错的!

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42023817

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档