PyRun_String() 中的访问冲突

Access violation in PyRun_String()

我在调用 Python 的 C 代码中遇到访问冲突错误。

我正在尝试从 Python 调用一个 sympy 函数并在 C 中处理结果。

#include <Python.h>

int main(int argc, char *argv[])
{
    PyObject *pmod, *pdict, *pValue;
    Py_Initialize();
    pmod  = PyImport_ImportModule("sympy");
    PyErr_Print();
    pdict = PyModule_GetDict(pmod);

    pValue = PyRun_String("x = symbols('x'); diff(cos(x), x)", Py_single_input, pdict, pdict);
    PyErr_Print();
    if (pValue != NULL) {
        //PyObject* pu = PyUnicode_AsEncodedString(pValue, "utf-8", "~E~");
        //printf("Result of call: %s\n", PyBytes_AS_STRING(pu));
        //Py_DECREF(pu);
        Py_DECREF(pValue);
        Py_DECREF(pmod);
        Py_DECREF(pdict);
    }
    else {
        PyErr_Print();
        return 1;
    }
    Py_FinalizeEx();
    return 0;
}

我想知道这种访问冲突的原因以及如何解决。我也想知道为什么显示结果的注释 printf 不起作用。

我的编译行是:

gcc probe.c `python3-config --cflags` `python3-config --ldflags` -fpic

我的Python版本是3.6.7。

提前致谢。

问题是您在不应该的时候破坏了 sympy 模块的字典。根据documentation for PyModule_GetDict,返回的字典引用是借来的,不是新的。因此,您不得对其调用 Py_DECREF。删除带有 Py_DECREF(pdict); 的行可以解决问题。

有关 Python documentation 的所有权和借用的更多信息:

Ownership can also be transferred, meaning that the code that receives ownership of the reference then becomes responsible for eventually decref’ing it by calling Py_DECREF() or Py_XDECREF() when it’s no longer needed—or passing on this responsibility (usually to its caller). When a function passes ownership of a reference on to its caller, the caller is said to receive a new reference. When no ownership is transferred, the caller is said to borrow the reference. Nothing needs to be done for a borrowed reference.