我想从C程序中调用python函数,但是PyDict_GetItemString总是返回NULL,因此程序会写“函数出错”。 main_module和main_dict不是NULL,我已经检查了它。
我尝试实现此处的代码 Call a Python function from within a C program
test.c file:
#include <stdlib.h>
#include "python3.7m/Python.h"
int main() {
PyObject* main_module = NULL;
PyObject* main_dict = NULL;
PyObject* function = NULL;
Py_Initialize();
PyObject* sys = PyImport_ImportModule("sys");
PyObject* path = PyObject_GetAttrString(sys, "path");
PyList_Append(path, PyUnicode_FromString("."));
PyObject* pName = PyUnicode_FromString("test");
main_module = PyImport_Import(pName);
main_dict = PyModule_GetDict(main_module);
char* func_name = "multiply";
function = PyDict_GetItemString(main_dict, func_name);
if (!function) {
printf("%s\n", "Something wrong in function");
}
Py_Finalize();
return 0;
}
test.py file:
def multiply():
return int(2*2)
compilation:
gcc test.c -o test -lpython3.7m -I /usr/lib/python3.7 -I /usr/include/python3.7m