一,安装环境sudo apt install libpython3.10-dev,安装C代码调用python的库函数和动态库
#include "Python.h"
int main()
{
Py_Initialize(); // 初始化python解释器
PyRun_SimpleString("print ('funny')");//在C语言调用print()打印字符串
Py_Finalize(); //释放python解释器占用的资源
return 0;
}
二、调用无参函数
#include<Python.h>
int main()
{
Py_Initialize();
PyObject *sys =PyImport_ImportModule("sys");
PyObject *path = PyObject_GetAttrString(sys, "path");
PyList_Append(path,PyUnicode_FromString("."));
PyObject *pModule = PyImport_ImportModule("nopara");
PyObject *pFunc = PyObject_GetAttrString(pModule, "say_funny");
PyObject *pValue = PyObject_CallObject(pFunc, NULL);
// 释放所有引用的Python对象
Py_DECREF(pValue);
Py_DECREF(pFunc);
Py_DECREF(pModule);
Py_Finalize();
return 0;
}
PyObject_CallObject(pFunc, NULL);无参调用函数