-1
我想爲Python編寫一個C擴展,如下所示,此代碼的目的是計算歐幾里得從浮點的2個列表中進行選擇。*** python中的錯誤:munmap_chunk():無效指針:0x00007fdfb8c28950 ***
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)
,所以我不能在調用此函數成功。
誰能幫我解決這個問題?非常感謝
我甚至不知道它有什麼問題。
順便說一句: 當我complie代碼,海灣合作委員會要求我加-fPIC,但是當我加-fPIC,該說的gcc找不到Python.h 最終我改變:
#include <Python.h>
這個:
#include <python2.7/Python.h>
那麼OK
當我評論的兩句話,代碼運行良好:
free(seq_a);
free(seq_b);
,但我認爲沒有2句,就會出現內存泄漏,因爲seq_a,seq_b不會被釋放
非常感謝,它的工作原理 – user3978288 2015-04-01 11:53:53