从C扩展返回引发分段错误

大家好,
最近,我一直在对Python进行C扩展。此扩展具有一个接受3D数组的函数(由
Pygame.surfarray.pixels3d
),将对此数组执行操作,然后返回它。
我的问题是,这个函数最基本的形式是在我的程序调用了58次之后抛出一个分段错误。输入始终是一个3D整数数组,第一维大小为70,第二个大小为36,第三个大小为3。我运行了一个测试,其中每个输入在各个方面都相同,但函数仍然有故障。
以下是代码:

选择 | 换行 | 行号
  1. static PyObject *
  2. TileTransform_getTransformedTile(TileTransform *self, PyObject *args)
  3. {
  4.     PyObject *source;
  5.  
  6.     //Parse the input parameters.
  7.     if (! PyArg_ParseTuple(args, "O", &source))
  8.         return NULL;
  9.  
  10.     return source;
  11. }

是不是有什么内存管理我做不到?
谢谢你的帮助!
~故事

# 回答1


原来,从存储参数的相同地址返回原始输入会出现问题。
如果我将PyObject转换为一个PyObject数组(如下所示),并且始终返回该数组而不是原始输入(前面,我的代码在不需要更改时返回原始输入),则该函数不会抛出我前面得到的分段错误。
有效的代码是..。

选择 | 换行 | 行号
  1. static PyObject *
  2. TileTransform_getTransformedTile(TileTransform *self, PyObject *args)
  3. {
  4.         PyObject *source;
  5.     PyArrayObject *sourceArray;
  6.  
  7.     //Parse the input parameters.
  8.         if (! PyArg_ParseTuple(args, "OO", &source))
  9.         return NULL;
  10.  
  11.     //Translate the source to an array, (source, type, minimum dimensions, maximum dimensions).
  12.     sourceArray = (PyArrayObject *) PyArray_ContiguousFromObject(source, PyArray_LONG, 0, 3);
  13.  
  14.         //Checks and alterations to the array here.
  15.  
  16.     return PyArray_Return(resultArray);
  17. }

希望这有助于防止其他人陷入同样的错误。
~故事

# 回答2


故事--感谢您的反馈!希望你的问题和解决方案能帮助其他人。

标签: python

添加新评论