我想为Python编写一个C扩展,如下所示,这段代码的目的是从2个 float 列表中计算欧几里得距离。
C 代码:
#include <python2.7/Python.h>
#include <math.h>
static PyObject* cutil_euclidean_dist(PyObject* self, PyObject* args) {
PyObject *seq_a, *seq_b;
int n;
float * array_a,* array_b;
PyObject *item;
printf("prepare to check input");
PyArg_ParseTuple(args,"iOO", &n , &seq_a, &seq_b);
if (!PySequence_Check(seq_a) || !PySequence_Check(seq_b)) {
PyErr_SetString(PyExc_TypeError, "expected sequence");
return NULL;
}
array_a =(float *)malloc(sizeof(float)*n);
array_b =(float *)malloc(sizeof(float)*n);
if (NULL == array_a || NULL == array_b){
PyErr_SetString(PyExc_TypeError, "malloc failed!");
return NULL;
}
printf("%d",array_a==NULL);
printf("%d",array_b==NULL);
printf("malloc yes ");
printf("n=%d",n);
int i;
for(i=0;i<n;i++){
printf("111");
item = PySequence_GetItem(seq_a,i);
printf("after get item");
if (!PyFloat_Check(item)) {
printf("in float check");
free(array_a); /* free up the memory before leaving */
free(array_b);
free(seq_a);
free(seq_b);
PyErr_SetString(PyExc_TypeError, "expected sequence of float");
return NULL;
}
array_a[i] = PyFloat_AsDouble(item);
printf("a=%f",array_a[i]);
Py_DECREF(item);
item = PySequence_GetItem(seq_b,i);
if(!PyFloat_Check(item)) {
free(array_a);
free(array_b);
free(seq_a);
free(seq_b);
PyErr_SetString(PyExc_TypeError, "expected sequence of float");
}
array_b[i] = PyFloat_AsDouble(item);
Py_DECREF(item);
}
printf("array analyze yes");
double sum = 0;
for(i=0;i<n;i++){
double delta = array_a[i] - array_b[i];
sum += delta * delta;
}
free(array_a);
free(array_b);
free(seq_a);
free(seq_b);
return Py_BuildValue("d",sqrt(sum));
}
static PyMethodDef cutil_methods[] = {
{"c_euclidean_dist", (PyCFunction)cutil_euclidean_dist,METH_VARARGS,NULL},
{NULL,NULL,0,NULL}
};
PyMODINIT_FUNC initcutil(void) {
Py_InitModule3("cutil", cutil_methods, "liurui's c extension for python");
}
Python 代码:
import cutil
cutil.c_euclidean_dist(2,[1.0,1.0],[2.0,2.0])
结果:
*** Error in `python': munmap_chunk(): invalid pointer: 0x00007fdfb8c28950 *** (core dumped)
所以我无法成功调用这个函数。
谁能帮我解决这个问题?非常感谢
我什至不知道它出了什么问题。
顺便说一下: 当我编译代码时,gcc要求我添加 -fPIC ,但是当我添加 -fPIC 时,说 gcc 找不到 Python.h 最终我改变了:
#include <Python.h>
进入此:
#include <python2.7/Python.h>
那就OK了
当我评论这两句话时,代码运行良好:
free(seq_a);
free(seq_b);
但我认为如果没有这两句话,就会出现内存泄漏,因为 seq_a , seq_b 将不会被释放
最佳答案
您只能使用free()
来释放使用malloc()
分配的内存。
seq_a
和 seq_b
不是通过 malloc
分配的。
此外,您还应该查看 Python 文档中的 PyObject
和引用计数章节。
关于python - *** 错误 `python' : munmap_chunk(): invalid pointer: 0x00007fdfb8c28950 ***,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29386288/