大家好,
最近,我一直在对Python进行C扩展。此扩展具有一个接受3D数组的函数(由
Pygame.surfarray.pixels3d
),将对此数组执行操作,然后返回它。
我的问题是,这个函数最基本的形式是在我的程序调用了58次之后抛出一个分段错误。输入始终是一个3D整数数组,第一维大小为70,第二个大小为36,第三个大小为3。我运行了一个测试,其中每个输入在各个方面都相同,但函数仍然有故障。
以下是代码:
- static PyObject *
- TileTransform_getTransformedTile(TileTransform *self, PyObject *args)
- {
- PyObject *source;
-
- //Parse the input parameters.
- if (! PyArg_ParseTuple(args, "O", &source))
- return NULL;
-
- return source;
- }
是不是有什么内存管理我做不到?
谢谢你的帮助!
~故事
# 回答1
原来,从存储参数的相同地址返回原始输入会出现问题。
如果我将PyObject转换为一个PyObject数组(如下所示),并且始终返回该数组而不是原始输入(前面,我的代码在不需要更改时返回原始输入),则该函数不会抛出我前面得到的分段错误。
有效的代码是..。
- static PyObject *
- TileTransform_getTransformedTile(TileTransform *self, PyObject *args)
- {
- PyObject *source;
- PyArrayObject *sourceArray;
-
- //Parse the input parameters.
- if (! PyArg_ParseTuple(args, "OO", &source))
- return NULL;
-
- //Translate the source to an array, (source, type, minimum dimensions, maximum dimensions).
- sourceArray = (PyArrayObject *) PyArray_ContiguousFromObject(source, PyArray_LONG, 0, 3);
-
- //Checks and alterations to the array here.
-
- return PyArray_Return(resultArray);
- }
希望这有助于防止其他人陷入同样的错误。
~故事
# 回答2
故事--感谢您的反馈!希望你的问题和解决方案能帮助其他人。