【发布时间】: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