从C调用Python时无法加载模块的问题求助
从C调用Python时无法加载模块的问题求助
我最近在做从C程序调用Python模块的功能,结果碰上个棘手的问题——不管怎么调整代码,都没法成功加载目标Python模块,折腾好半天都没解决,想请大家帮忙分析下问题出在哪!
最开始我写了这段代码,指定了模块的绝对路径,但PyImport_ImportModule()返回的一直是NULL,连错误提示都没有:
PyObject *python_module; char *module_filename = "/mnt/USB3/C/Python_from_C/python_processes"; Py_Initialize(); python_module = PyImport_ImportModule(module_filename); if(python_module == NULL) { printf ( "Failed to load module \"%s\"\n", module_filename ); getchar(); }
对应的python_processes.py文件确实存在,我也试了好多种Python初始化的方案,但结果全都是模块加载失败。
后来我换了一种写法,结果程序直接崩溃了:
Py_Initialize(); python_file_name_pValue = PyUnicode_DecodeFSDefault("python_processes.py"); python_file = PyImport_Import(python_file_name_pValue); python_function = PyObject_GetAttrString(python_file, "image_processing");
我还专门写了一个加载函数,结果还是加载模块失败:
PyObject *load_python_function3 ( char *python_file_name, char *python_function_name ) { PyObject *pName, *pModule, *python_function; pName = PyUnicode_FromString(python_file_name); pModule = PyImport_Import(pName); if(pModule == NULL) { printf("Failed to load python_moduke\n"); getchar(); } python_function = PyObject_GetAttrString(pModule, python_function_name); if(python_function == NULL) { printf("Failed to load python_function\n"); getchar(); } return python_function; }
有没有大佬能帮我看看,到底是哪里出了问题?为什么这些方法都没法成功加载Python模块或者函数呢?
备注:内容来源于stack exchange,提问作者user2731097
相关产品推荐
相关产品推荐

