【问题标题】:Numpy C API - Using PyArray_Descr for array creation causes segfaultsNumpy C API - 使用 PyArray_Descr 创建数组会导致段错误
【发布时间】:2017-03-20 20:41:22
【问题描述】:

我正在尝试使用 Numpy C API 在 C++ 中创建 Numpy 数组,并包装在一个实用程序类中。大多数事情都按预期工作,但是每当我尝试使用采用PyArray_Descr* 的函数之一创建数组时,程序会立即出现段错误。设置PyArray_Descr 进行创建的正确方法是什么?

一个不起作用的代码示例:

PyMODINIT_FUNC
PyInit_pysgm()
{
    import_array();
    return PyModule_Create(&pysgmmodule);
}

// ....

static PyAry zerosLike(PyAry const& array)
{
    PyArray_Descr* descr = new PyArray_Descr;
    Py_INCREF(descr); // creation function steals a reference
    descr->type = 'H';
    descr->type_num = NPY_UINT16;
    descr->kind = 'u';
    descr->byteorder = '=';
    descr->alignment = alignof(std::uint16_t);
    descr->elsize = sizeof(std::uint16_t);
    std::vector<npy_intp> shape {array.shape().begin(), array.shape().end()};
    // code segfaults after this line before entering PyAry constructor
    return PyAry(PyArray_Zeros(shape.size(), shape.data(), descr, 0));
}

(使用 uint16 进行测试)。

我没有设置typeobj 字段,这可能是唯一的问题,但我无法确定PyTypeObject 类型的适当值是什么。

编辑This page 列出了不同类型的 ScalarArray PyTypeObject 实例。添加行

descr->typeobj = &PyUShortArrType_Type;

没有解决问题。

【问题讨论】:

    标签: python c++ numpy


    【解决方案1】:

    尝试使用

    descr = PyArray_DescrFromType(NPY_UINT16);
    

    我最近才针对 numpy C-API 进行编写,但据我收集的 PyArray_Descr 基本上是来自 python-land 的 dtype。如果可以,您应该自己构建这些并使用 FromType 宏。

    【讨论】:

    • 哎呀 - 我本来想回到这个 - 你是对的,这就是我找到的答案。
    猜你喜欢
    • 1970-01-01
    • 2014-07-04
    • 2020-08-29
    • 1970-01-01
    • 2014-10-19
    • 1970-01-01
    • 2023-02-09
    • 2015-01-10
    • 1970-01-01
    相关资源
    最近更新 更多