我希望使用C++将一个简单的Pybind11函数集成到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的函数中,我在Anaconda中使用Python3.5.2。在正式文件之后,我编译脚本如下:
c++ -O3 -shared -std=c++11 -I /Users/SECSCL/anaconda3/include/python3.5m `python-config --cflags --ldflags` example.cpp -o example.so我不知道“”部分到底代表什么,但我知道它会导致问题。我尝试了三种选择:
总之,我的问题是:如何编译我的代码以便从python3.5 3.5加载它?或者更准确地说:我需要用什么替换‘python’语句?
发布于 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。
现在,您可以按以下方式调用编译:
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]..。挺不错的!
https://stackoverflow.com/questions/42023817
复制相似问题