PyRun_SimpleString调用会导致内存损坏

PyRun_SimpleString call cause memory corruption?

本文关键字:内存 损坏 SimpleString 调用 PyRun      更新时间:2023-10-16

我正在尝试在C++中使用Python并具有以下代码。我打算在用户输入路径上解析和执行sys.path.append。看起来对PyRun_SimpleString的调用导致了某种溢出到该类的私有类 var 中。这是怎么发生的?我尝试了各种缓冲区大小 50、150、200,它没有改变输出。

class Myclass
{
    ...
    private:
        char *_modName;
        char *_modDir;
};
Myclass::Myclass()
{
    Py_Initialize();
    PyRun_SimpleString("import sys");
    PyRun_SimpleString((char *)"sys.path.append('/home/userA/Python')");
}
Myclass::init()
{
    // this function is called before Myclass::test()
    // a couple other python funcitons are called as listed below. 
    // PyString_FromString, PyImport_Import, PyObject_GetAttrString, PyTuple_New, PyTuple_SetItem, PyObject_CallObject, PyDict_GetItemString
}
Myclass::test()
{
    char buffer[150];
    char *strP1 = (char *)"sys.path.append('";
    char *strP2 = (char *)"')";
    strcpy (buffer, strP1);
    strcat (buffer, _modDir);
    strcat (buffer, strP2);
    printf("Before %sn", _modDir);
    printf("Before %sn", _modName);
    PyRun_SimpleString(buffer);
    printf("After %sn", _modName);
} 

这是输出。仅供参考,我使用 a,b,c,d,f 仅用于说明目的。它几乎像PyRun_SimpleString(缓冲区)一样填充缓冲区的末端_modName。

Before /aaa/bbb/ccc/ddd
Before ffffff
After cc/ddd'

感谢Klamer Schutte在正确的方向上暗示。我的代码中的 DECRF 是罪魁祸首。我猜,对参考的工作原理不熟悉。DECREF调用发布了pValue以及_modName指向的内容。一个更初学者的问题,我应该在_modName作业后添加一个Py_INCREF(pValue)吗?

_modName = PyString_AsString (PyDict_GetItemString(pValue, (char*)"modName"));
Py_DECREF(pValue);