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

标签 python c python-3.x import embedding

我正在构建将使用 Python 插件的 C 应用程序。当尝试从另一个 Python 模块调用方法时,函数 PyImport_ImportModule() 似乎正确导入了模块,然后我尝试使用 PyObject_GetAttrString() 从该模块获取函数> 而我得到的全部都是空的。

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

主.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;
}

测试.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.

关于python - 将 Python 嵌入到 C 中 - 无法从 python 模块导入方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57108881/

相关文章:

python - 从请求中获取字节响应

python - 为什么Python(IronPython)在使用bin这个词时会报 "Illegal characters in path"?

python - 如何使用递归获取节点邻居?

python - 将带括号的内容过滤到 Python 列表中

c - Glade 3 和 C,按钮和文本框的信号处理

在运行时检查 libxml2.so 的构建参数

python - 如何在 Bottle 框架中渲染阿拉伯字符串?

C 程序一次读取一个字符,但永远不会到达 EOF?

python - 使用 Python 3 从动态 HTML 表中提取数据

python - Tensorboard:无标量值