据我所知,执行此操作的一个好方法是使用 Boot.Python图书馆,例如 this simple example ;请不要推荐像 Cython 这样的替代品作为解决方案。但是当我尝试使用 boost::python
数据类型时,我的 cpp 文件无法构建。
example_boost.cpp:
#include <boost/python.hpp>
#include <boost/python/numpy.hpp>
#include <iostream>
namespace bpy = boost::python;
namespace bnp = boost::python::numpy;
void do_stuff(const bnp::ndarray& input_array) {
...
};
/*
* This is a macro Boost.Python provides to signify a Python extension module. This enables me to import example_boost.cpp and call do_stuff() within a Python file.
*/
BOOST_PYTHON_MODULE(crf) {
// Expose the functions
boost::python::def("compute_factor_out_msgs", compute_factor_out_msgs);
}
运行 make
...
Undefined symbols for architecture x86_64:
"boost::python::converter::object_manager_traits<boost::python::numpy::ndarray>::get_pytype()", referenced from:
boost::python::detail::caller_arity<1u>::impl<OutMessages (*)(boost::python::numpy::ndarray const&), boost::python::default_call_policies, boost::mpl::vector2<OutMessages, boost::python::numpy::ndarray const&> >::operator()(_object*, _object*) in example_boost.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [example_boost.so] Error 1
注意事项:
-
如果我不使用
make
是成功的,所以我的 Makefile 是正确的。- 我在 Mac OSX El Capitan 上通过自制软件安装了 Boost v 1.63.0
- 使用 C++ 11 和 Python 2.7
bpy
和 bnp
类型,最佳答案
已发布示例代码的两个问题:
要解决 make 问题,Makefile 还必须链接
-lboost_numpy
。即使它可以编译,结果也会是段错误(堆栈溢出),因为我们需要先用
Py_Initialize(); bnp::初始化();
解释为 here .
关于python - 用 Boost Python 包装 C++ 函数——numpy 数组类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42613050/