【问题标题】:Passing a numpy array FROM C++ using boost python使用 boost python 从 C++ 传递一个 numpy 数组
【发布时间】:2012-10-22 16:11:15
【问题描述】:

我需要将一个 numpy 数组从 C++ 传递给一个 python 函数。 代码如下。 蟒蛇方面:

import numpy as np
import  convert as cv

def f(x):
  x[0] = 5.
  return len(x)

if __name__ == '__main__':
  y = np.array([1., 2., 3., 4.])
  x = cv.func_n(f, y)
  print x

C++ 方面:

#include <iostream>
#include <boost/python.hpp>

using namespace boost::python;
double func_n(PyObject* f, numeric::array &x)
{
  std::cerr << "Inside func_n\n";
  return boost::python::call<double>(f, boost::ref(x));
}

BOOST_PYTHON_MODULE(convert)
{
  numeric::array::set_module_and_type("numpy", "ndarray");

  def("func_n", &func_n);

}

C++ 代码应该做的是将一个 python functopn 和一个 numpy 数组作为两个参数,然后将 numpy 数组传递给 python 函数。 我得到的错误是:

Traceback (most recent call last):
  File "mm.py", line 11, in <module>
    x = cv.func_n(f, y)
TypeError: No Python class registered for C++ class class boost::python::numeric::array

为什么?我是否必须在解释器的递归调用期间注册模块,如果是,如何注册?

【问题讨论】:

  • 继续:使用 return boost::python::call(f, x);而不是 return boost::python::call(f, boost::ref(x));帮助,代码工作正常。 boost::ref(x) 有什么作用?我的印象是 boost::python::call 复制了参数。原来它没有。这在哪里可以澄清?

标签: python boost numpy


【解决方案1】:

boost::ref(x) 返回一个boost::reference_wrapper&lt;T&gt;,它允许您将引用传递给按值函数。

boost::python::call docs 表明参数根据它们的类型被区别对待。如果 arg 是 boost::reference_wrapper&lt;T&gt;,它会有效地将对 x 的引用传递给 Python。

因此,在上面的代码中,您将对 numeric::array 的引用传递给 Python。您从 Python 调用的函数也接受引用。

现在我不确定这一点,但我怀疑由于您实际上从未在 Python/C++ 之间传递 numeric::array,因此 boost::python 决定不包装它或创建转换器(因为您真的只是传递地址)。这可能是您看到没有为 numeric::array 类型注册 Python 类的原因。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    • 1970-01-01
    • 2019-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-02
    相关资源
    最近更新 更多