【发布时间】:2020-05-11 23:59:22
【问题描述】:
所以正如标题所暗示的那样,我正在开发一个 c++ 项目,我需要调用一个 python 模块,将它保存为一个对象,并多次调用它的一个方法。您可以在下面找到包含 python 对象的类的代码。目前,它是在 for 循环中实现的,该循环多次调用该方法。实例化类工作正常,以及对类的第一次调用。但是,在 for 循环的第一个循环完成后,程序会崩溃,并出现“free(): invalid size”或有时“double free or corruption”的错误。我尝试使用 valgrind 来尝试追踪内存泄漏,但是我得到了很多我不太了解的 pythonCApi 调用的痕迹。
#include <python2.7/Python.h>
#include <iostream>
#include <algorithm>
#include "predictor.hpp"
using namespace std;
predictor::predictor()
{
Py_Initialize();
pName = PyString_FromString("predictor");
pModule = PyImport_Import(pName);
Py_XDECREF(pName);
if (pModule == nullptr) {
PyErr_Print();
std::cerr << "Fails to import the module predictor, check installation.\n";
}
// dict is a borrowed reference.
dict = PyModule_GetDict(pModule);
if (dict == nullptr) {
PyErr_Print();
std::cerr << "Fails to get the dictionary, check predictor installation.\n";
Py_XDECREF(pModule);
}
Py_XDECREF(pModule);
// Builds the name of a callable class
python_class = PyDict_GetItemString(dict, "Predictor");
if (python_class == nullptr || python_class == NULL) {
PyErr_Print();
std::cerr << "Fails to get the Python class, check predictor installation.\n";
Py_XDECREF(dict);
}
Py_XDECREF(dict);
// Creates an instance of the class
if (PyCallable_Check(python_class)) {
object = PyObject_CallObject(python_class, nullptr);
if (object == NULL)
{
cerr << "Fails to create object.";
Py_XDECREF(python_class);
}
Py_XDECREF(python_class);
} else {
PyErr_Print();
std::cout << "Cannot instantiate the Python class" << std::endl;
Py_XDECREF(python_class);
}
pMethod = PyString_FromString("predict_all");
}
predictor::~predictor()
{
Py_XDECREF(pMethod);
Py_XDECREF(object);
Py_Finalize();
}
long predictor::predict(string rule)
{
PyObject *pRule = PyString_FromString(rule.c_str());
PyObject *value = PyObject_CallMethodObjArgs(object, pMethod, pRule, NULL);
long endValue = PyInt_AsLong(value);
if (endValue == -1)
{
if(!PyErr_Occurred())
{
PyErr_Print();
cerr << "";
Py_XDECREF(value);
Py_XDECREF(pRule);
return NULL;
}
//PyErr_Print();
}
Py_XDECREF(value);
Py_XDECREF(pRule);
return endValue;}
【问题讨论】:
标签: python c++ python-embedding