出现的问题 找不到python的头文件
1、更换镜像
2、更新python : sudo apt-get install python3.10-dev
1、包含Python.h头文件,以便使用Python API。
2、使用void Py_Initialize()初始化Python解释器,
3、使用PyObject *PyImport_ImportModule(const char *name)和PyObject *PyObject_GetAttrString(PyObject *o, const char *attr_name)获取sys.path对象,并利用 int PyList_Append(PyObject *list, PyObject *item)将当前路径.添加到sys.path中,以便加载 当前的Python模块(Python文件即python模块)。
4、使用PyObject *PyImport_ImportModule(const char *name)函数导入Python模块,并检查是否 有错误。
5、使用PyObject *PyObject_GetAttrString(PyObject *o, const char *attr_name)函数获取 Python函数对象,并检查是否可调用。
6、使用PyObject *PyObject_CallObject(PyObject *callable, PyObject *args)函数调用 Python函数,并获取返回值。
7、使用void Py_DECREF(PyObject *o)函数释放所有引用的Python对象。
8、结束时调用void Py_Finalize()函数关闭Python解释器。
garbage.c
#include <Python.h>
#include "garbage.h"
#include <string.h>
PyObject *pModule = NULL;
PyObject *pPath = NULL;
PyObject *pSysPath = NULL;
PyObject *pFunc = NULL;
PyObject *pArgs = NULL;
PyObject *pResult = NULL;
void garbage_init(void)
{
// 1. 初始化Python解释器
Py_Initialize();
// 2. 获取sys.path并添加当前路径
pSysPath = PySys_GetObject("path");
if (pSysPath == NULL) {
fprintf(stderr, "Failed to get sys.path\n");
goto fail;
}
pPath = PyUnicode_FromString(".");
if (pPath == NULL) {
fprintf(stderr, "Failed to create path object\n");
goto fail;
}
if (PyList_Append(pSysPath, pPath) == -1) {
fprintf(stderr, "Failed to append to sys.path\n");
goto fail;
}
}
void garbage_final(void)
{
// 8. 关闭Python解释器
Py_Finalize();
}
char* garbage_category(char *category) {
// 3. 导入Python模块
pModule = PyImport_ImportModule("garbage");
if (pModule == NULL) {
fprintf(stderr, "Failed to import module\n");
goto fail;
}
// 4. 获取Python函数对象
pFunc = PyObject_GetAttrString(pModule, "alibaba_garbage");
if (pFunc == NULL || !PyCallable_Check(pFunc)) {
fprintf(stderr, "Function not found or not callable\n");
goto fail;
}
// 5. 准备调用函数的参数
pArgs = PyTuple_New(0); // 如果函数没有参数,传递一个空元组
if (pArgs == NULL) {
fprintf(stderr, "Failed to create arguments\n");
goto fail;
}
// 6. 调用Python函数
pResult = PyObject_CallObject(pFunc, pArgs);
if (pResult == NULL) {
fprintf(stderr, "Function call failed\n");
goto fail;
}
char* result = NULL;
if(!PyArg_Parse(pResult,"s",&result)){
fprintf(stderr, "Failed to return\n");
goto fail;
}
printf("result = %s\n",result);
category = (char*)malloc(sizeof(char*)*(strlen(result)+1));
memset(category,'\0',sizeof(char*)*(strlen(result)+1))
strcpy*(category,result);
return category;
// 7. 清理Python对象
fail:
Py_DECREF(pArgs);
Py_XDECREF(pFunc); // 使用 Py_XDECREF 来处理可能为 NULL 的对象
Py_XDECREF(pModule); // 同上
Py_XDECREF(pPath);
Py_XDECREF(pResult);
}
garbage.h
#ifndef __GARBAGE__H
#define __GARBAGE__H
void garbage_init(void);
void garbage_final(void);
char* garbage_category(char *category);
#endif
main.c
#include <stdio.h>
#incldeu "garbage.h"
int main()
{
char *category = NULL;
garbage_init();
category = garbage_category(category);
printf("category = %s\n",category)
garbage_final();
if(category){
free(category);
}
}