我无法在以下代码中找出内存泄漏的原因; Valgrind在执行以下功能时报告内存。由于我对Py_INCREF和Py_DECREF宏缺乏了解,可能会发生这种情况。
这里是c ++代码
if (process.argv.length < 3) {
console.error("A file path is required");
process.exit(1);
}
这里是Python函数
#include <stdio.h>
#include <Python.h>
#include "numpy/arrayobject.h"
#include <ctime>
#include <iostream>
using namespace std;
int main() {
PyObject *pName = NULL;
PyObject *pModule = NULL;
PyObject *pFunc = NULL;
PyObject *pArgs = NULL;
PyObject *pValue = NULL;
PyObject *vec = NULL;
PyObject *vec1 = NULL;
const char* script = "TestScript";
const char* function = "test";
Py_Initialize();
pName = PyUnicode_FromString(script);
pModule = PyImport_Import(pName);
// Deleting memory for object pName
Py_DECREF(pName);
import_array1(-1);
if (pModule != NULL) {
pFunc = PyObject_GetAttrString(pModule, function);
if (pFunc && PyCallable_Check(pFunc)) {
// define a vector
double* v = new double[5];
v[0] = 1.0;
v[1] = 2.0;
v[2] = 3.0;
v[3] = 4.0;
v[4] = 5.0;
double* v1 = new double[5];
v1[0] = 1.0;
v1[1] = 2.0;
v1[2] = 3.0;
v1[3] = 4.0;
v1[4] = 5.0;
npy_intp vdim[] = { 5 };
vec = PyArray_SimpleNewFromData(1, vdim, (int)PyArray_DOUBLE, (void*)v);
vec1 = PyArray_SimpleNewFromData(1, vdim, (int)PyArray_DOUBLE, (void*)v1);
pArgs = PyTuple_New(2);
Py_INCREF(vec); // If I don't do this, I get segfault in Py_Finalize**
Py_INCREF(vec1); // If I don't do this, I get segfault in Py_Finalize**
PyTuple_SetItem(pArgs, 0, vec);
PyTuple_SetItem(pArgs, 1, vec1);
pValue = PyObject_CallObject(pFunc, pArgs);
Py_DECREF(pArgs);
Py_XDECREF(vec);
Py_XDECREF(vec1);
delete [] v;
delete [] v1;
if (pValue != NULL) {
printf("Result of call: %f\n", PyFloat_AsDouble(pValue));
Py_DECREF(pValue);
}
Py_DECREF(pFunc);
} else {
if (PyErr_Occurred()) {
PyErr_Print();
fprintf(stderr, "Cannot find function \"%s\"\n", function);
}
}
Py_DECREF(pModule);
} else {
PyErr_Print();
return 1;
}
Py_Finalize();
return 0;
}
这里是Valgrind报告的摘要。
def test(a, b):
print("Python::test")
print(a)
print(b)
return 1