PyRun\u String()中的访问冲突

2024-10-16 20:49:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我在调用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。你知道吗

提前谢谢。你知道吗


Tags: pyconfigreturnpython3intpyobjectprintsympy
1条回答
网友
1楼 · 发布于 2024-10-16 20:49:28

问题是您正在销毁sympy模块的字典,而您不应该这样做。根据documentation for ^{},返回的字典引用是借用的,而不是新的。因此,您不能对它调用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.

相关问题 更多 >