【问题标题】:How to create a numpy array of boost::python::object types如何创建 boost::python::object 类型的 numpy 数组
【发布时间】:2020-11-24 07:16:59
【问题描述】:

我正在尝试创建一个 2x2 numpy 的 python 对象数组:

#include <boost/python.hpp>
#include <boost/python/numpy.hpp>
int main()
{
    Py_Initialize();
    boost::python::numpy::initialize();
    boost::python::tuple shape = boost::python::make_tuple(2, 2);
    boost::python::object obj;
    boost::python::numpy::dtype dt = boost::python::numpy::dtype(obj);
    boost::python::numpy::ndarray array = boost::python::numpy::empty(shape, dt);
    std::cout << "Datatype is: " << boost::python::extract<char const *> boost::python::str(array.get_dtype())) << std::endl;
}

但输出是“数据类型为:float64”而不是 python 对象类型。

我做错了什么?

我怀疑我在滥用 dtype 构造函数。

【问题讨论】:

    标签: c++ boost boost-python


    【解决方案1】:

    您正确地使用了dtype 构造函数;是 obj 造成了麻烦。

    默认构造boost::python::object obj;obj 设置为'None' Python 对象。与'None' 关联的dtypeNPY_DEFAULT 数组描述符类型。在创建 numpy 数组时映射到 double,这解释了您的输出。 (从 Python 的角度来看,这是有道理的 - 默认的 numpy 数组类型是双精度浮点类型。)

    您可以使用对象类型 (NPY_OBJECT) 构造 dtype

    boost::python::numpy::dtype dt = boost::python::numpy::dtype(boost::python::object("O"));
    

    在您的情况下,这是解决方法。我还冒昧地使用了匿名临时文件,这就是 Boost 文档中的做法。 "O" 表示对象类型。

    【讨论】:

      猜你喜欢
      • 2020-08-04
      • 1970-01-01
      • 2011-12-06
      • 2015-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多