我在调用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 ^{Py_DECREF
。删除带有Py_DECREF(pdict);
的行修复了该问题。你知道吗有关所有权和从Python documentation借款的更多信息:
相关问题 更多 >
编程相关推荐