将 Python 嵌入到 C 中 - 无法从 python 模块导入方法

Embedding Python into C - can't import method from python module

我正在构建将使用 Python 插件的 C 应用程序。当尝试从另一个 Python 模块调用方法时,函数 PyImport_ImportModule() 似乎正确导入了模块,然后我尝试使用 PyObject_GetAttrString() 从该模块获取函数以及我得到的所有内容为空。

我已经尝试使用 PyModule_GetDict()PyDict_GetItemString() 从模块中获取方法,但效果是一样的。

main.c:

#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;
}

test.py:

def myfun():
  c = 123 + 123
  print('the result is: ', c)

myfun()

我得到的结果是:

Can't find method: Success
Segmentation fault (core dumped)

当我使用 gdb 调试器时,输出是:

pModule = (PyObject *) 0x7ffff5a96f48
pMethod = (PyObject *) 0x0

您的程序没有运行,因为正在导入的模块是 test built-in module,而不是您的 test.py 脚本。这是因为您正在 将当前目录附加 sys.path,因此在列表中的所有其他已存在路径之后检查它。您应该 将它插入列表的开头,以便首先检查它。

这会起作用:

PyObject *sys = PyImport_ImportModule("sys");                                                                                                                                                                     
PyObject *path = PyObject_GetAttrString(sys, "path");                                                                                                                                                     
PyList_Insert(path, 0, PyUnicode_FromString("."));

顺便说一下,您应该先 #include Python header,如文档中所述:

Note: Since Python may define some pre-processor definitions which affect the standard headers on some systems, you must include Python.h before any standard headers are included.