7.c语言调用python

c语言调用python

查看是否存在编译环境:

dpkg -l |grep libpython3 | grep dev

如果没有输出,执行环境搭建:

sudo apt install python3-dev #自动匹配
或
sudo apt install python3.10-dev
#sudo apt install libpython3.10-dev  # 或 libpython3.9-dev 或 libpython3.8-dev

1.简单调用输出

c语言编写

#include "Python.h"
int main()
{
    Py_Initialize(); // 初始化
    PyRun_SimpleString("print ('funny')");//执行python语法
    Py_Finalize(); //释放资源
}

编译:(上面安装的是3.8的dev)

gcc simpledemo.c -o simpledemo -I /usr/include/python3.10 -l python3.10
./simpledemo

上面代码的解释:

• 首先包含Python.h头文件,这是Python API的头文件,用于访问Python对象和函数

• 其次在程序开始时使用Py_Initialize()函数初始化Python解释器。这样可以在C程序中执行Python代码

• 然后使用PyRun_SimpleString()函数执行一段简单的Python代码,例如打印"funny"。需要传递一个字

符串作为参数,表示要执行的Python代码,如print ('funny')这么一个Python代码字符串。

函数说明:
int PyRun_SimpleString(const char *command)
这是针对下面 PyRun_SimpleStringFlags() 的简化版接口,将 PyCompilerFlags* 参数设为 NULL;
传参就是python执行语句。

• 最后在程序结束时使用Py_Finalize()函数关闭Python解释器,并释放资源。

2.调用无参函数

python中定义一个无参函数打印,c语言去调用函数执行

#nopara.py文件
def funny():
    print("hello")

c语言实现调用:

实现流程:

#if 0
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解释器。
相关的函数参数说明参考网站(网站左上角输入函数名即可开始搜索):
https://docs.python.org/zh-cn/3/c-api/import.html
#endif

实现代码:

#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");
        if(!pModule){
                PyErr_Print();
                printf("Error:failed to load nopara.py\n");
        }

        PyObject *pFunc = PyObject_GetAttrString(pModule,"funny");
        if(!pFunc){
                PyErr_Print();
                printf("Error:failed to load funny\n");
        }
    
        PyObject *pValue = PyObject_CallObject(pFunc,NULL);
        if(!pValue){
                PyErr_Print();
                printf("Error:function call failed\n");
        }
		//释放资源
        Py_DECREF(pValue);
        Py_DECREF(pFunc);
        Py_DECREF(pModule);
        Py_DECREF(path);
        Py_DECREF(sys);
        Py_Finalize();

        return 0;
}

3.调用有参函数,并返回

python定义返回值

#para.py
def funny(str):
    print(str)
    return "123"+str

c语言实现:

  • 传参:构造一个字符串类型的PythonObject,"(s)"表示字符类型

    • char *categroy = "comedy";
      PyObject *pArgs = Py_BuildValue("(s)",categroy);
      
  • 返回值:使用PyArg_Parse解析"s"表示解析返回值类型

    • PyArg_Parse(pValue,"s",&result)
      

para.c

#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("para");
        if(!pModule){
                PyErr_Print();
                printf("Error:failed to load para.py\n");
        }

        PyObject *pFunc = PyObject_GetAttrString(pModule,"funny");
        if(!pFunc){
                PyErr_Print();
                printf("Error:failed to load funny\n");
        }

        char *categroy = "comedy";
        PyObject *pArgs = Py_BuildValue("(s)",categroy);
        PyObject *pValue = PyObject_CallObject(pFunc,pArgs);
        if(!pValue){
                PyErr_Print();
                printf("Error:function call failed\n");
        }

        char *result = NULL;
        if(!PyArg_Parse(pValue,"s",&result)){
                PyErr_Print();
                printf("Error: parse failed");
        }
        printf("result:%s\n",result);

        Py_DECREF(pValue);
        Py_DECREF(pFunc);
        Py_DECREF(pModule);
        Py_DECREF(path);
        Py_DECREF(sys);
        Py_Finalize();

        return 0;
}
posted @ 2025-05-29 11:16  站着说话不腰疼  阅读(58)  评论(0)    收藏  举报