【问题标题】:PyArray_Check / PyArray_CheckExact gives segmentation faultPyArray_Check / PyArray_CheckExact 给出分段错误
【发布时间】:2017-03-16 12:46:45
【问题描述】:

在 c++ 中,我定义了以下模块:

#include <boost/python.hpp>
#include <numpy/arrayobject.h>

bool foo(PyObject *obj)
{
    if (!PyArray_CheckExact(obj))
        return false;

    PyArrayObject* arr = reinterpret_cast<PyArrayObject*>(obj);

    if (PyArray_NDIM(arr) != 2)
        return false;

    return true;    
}

BOOST_PYTHON_MODULE(pyMod)
{
    using namespace boost::python;

    import_array();

    def("foo", foo);
}

在 python 中,我执行以下操作

import numpy as np
import myMod

if __name__ == "__main__":
    arr = np.zeros(shape=(100, 100), dtype=np.uint8)

    myMod.foo(arr)

这会在执行对 PyArray_CheckExact 的调用时产生分段错误。去掉勾选,函数运行正常,强制转换成功。

我试过了:

bool foo(PyObject *obj)
{
    if (obj->ob_type->ob_type != &PyArray_Type)
        return false;

    PyArrayObject* arr = reinterpret_cast<PyArrayObject*>(obj);

    if (PyArray_NDIM(arr) != 2)
        return false;

    return true;    
}

这也是段错误。似乎 Numpy API 中的某些内容未正确初始化。我在 Windows 上使用 Anaconda2 32 位。

关于为什么会出现此段错误的任何想法?

【问题讨论】:

  • 我想你并没有完全理解 boost_python!你不应该直接使用它来处理 PyObject*,你应该使用 boost::python::object 来代替。
  • 无论如何,代码是有效的,并且您可能有一些库损坏以便接收 segvfault。尝试重新安装它。还有一点,第一个ifcondition 里面应该有一个not
  • 但是 numpy 对象不是 boost::python 对象。应该 foo() 有一个 boost::python::object 作为输入,然后我使用 boost::python::object::ptr() 来获取 PyObject?我找到的大多数示例代码都按照我上面的方式进行。

标签: python c++ numpy boost-python


【解决方案1】:

你第一次打电话吗

import_array();

在您的 C 代码中?如果不是,这将导致段错误。

这是影响我的问题。

只有 2 种方式会导致问题。

  1. PyArrayObj 为 NULL
  2. import_array() 尚未调用。

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多