我正在构建使用Python插件的C应用程序。当尝试从另一个Python模块调用该方法时,PyImport_ImportModule()
似乎正确地导入了该模块,然后我尝试使用PyObject_GetAttrString()
从该模块获取该函数,得到的结果是null。在
我已经尝试使用PyModule_GetDict()
和PyDict_GetItemString()
从模块中获取方法,但是效果是一样的。在
主控室:
#include <stdio.h>
#include <python3.6/Python.h>
int main()
{
PyObject *arg, *pModule, *ret, *pFunc, *pValue, *pMethod, *pDict;
Py_Initialize();
PyObject *sys = PyImport_ImportModule("sys");
PyObject *path = PyObject_GetAttrString(sys, "path");
PyList_Append(path, PyUnicode_FromString("."));
pModule = PyImport_ImportModule("test");
if(pModule == NULL)
{
perror("Can't open module");
}
pMethod = PyObject_GetAttrString(pModule, "myfun");
if(pMethod == NULL)
{
perror("Can't find method");
}
ret = PyEval_CallObject(pMethod, NULL);
if(ret == NULL)
{
perror("Couldn't call method");
}
PyArg_Parse(ret, "&d", pValue);
printf("&d \n", pValue);
Py_Finalize();
return 0;
}
在测试.py公司名称:
^{pr2}$我得到的结果是:
Can't find method: Success
Segmentation fault (core dumped)
当我使用gdb调试器时,输出是:
pModule = (PyObject *) 0x7ffff5a96f48
pMethod = (PyObject *) 0x0
您的程序没有编写,因为要导入的模块是^{} built-in module ,而不是您的
test.py
脚本。这是因为您正在将当前目录附加到sys.path
,因此它会在列表中其他已存在路径之后进行检查。您应该将其插入到列表的开头,以便先检查它。在这将起作用:
顺便说一下,您应该先
#include
Python头,如文档中所述:相关问题 更多 >
编程相关推荐