【问题标题】:Wrap C++ function with Boost Python -- numpy array types用 Boost Python 包装 C++ 函数——numpy 数组类型
【发布时间】:2017-03-05 19:39:30
【问题描述】:

据我所知,一个好方法是使用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

注意事项:

  • 如果我不使用 bpybnp 类型,make 是成功的,所以我的 Makefile 是正确的。
  • 我在 Mac OSX El Capitan 上通过自制软件安装了 Boost v 1.63.0
  • 使用 C++ 11 和 Python 2.7

【问题讨论】:

  • 如果我不使用bpybnp 类型,make 是成功的,所以我的 Makefile 是正确的。 不,它错过了链接器标志在bpybnp 中提供符号的库。

标签: python c++ macos numpy boost


【解决方案1】:

贴出的示例代码有两个问题:

  1. 要解决 make 问题,Makefile 还必须链接 -lboost_numpy

  2. 即使它会编译,结果也会是段错误(堆栈溢出),因为我们需要先初始化

    Py_Initialize(); bnp::initialize();

正如here 解释的那样。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-20
    • 1970-01-01
    • 1970-01-01
    • 2020-11-24
    • 2012-04-23
    • 2013-09-23
    • 2016-11-08
    • 1970-01-01
    相关资源
    最近更新 更多