Loading

C和python混合编程

python调用C程序

依赖于python的cytpes模块,C/C++将程序编译成dll动态库,使用ctypes.CDLL函数加载动态库,然后可以在python文件中条用dll中的函数。

在windows环境下,以简单的两数相加函数为例:

# sum.c
int sum(int a, int b) {
    return a + b;
}

将该文件编译成动态库:

gcc -fPIC -shared sum.c -o sum.dll

在python文件中调用:

# callSum.py
import ctypes
dll = ctypes.CDLL("./sum.dll")
a = 5
b = 9
c = dll.sum(a, b)

C调用python程序

C程序可以通过Python.h头文件中的函数调用python程序。

还是以两数相加函数为例:

# getsum.py
def sum(a, b):
    return a + b

在C文件中调用:

// callsum.c
#include <Python.h>
int main() {
    int a = 5, b = 9;
    Py_Initialize();  // 初始化python环境
    
    PyObject *pModule = PyImport_ImportModule("getsum");  // 导入Python模块
    if(!pModule) {
        return -1;
    }
    PyObject *pFunction = PyObject_GetAttrString(pModule, "sum");  // 获取函数对象
    if(!pFunction) {
        return -1;
    }
    PyObject *pArgs = PyTuple_New(2);  // 函数多个参数可构造元组进行传参
    PyTuple_SetItem(pArgs, 0, Py_BuildValue("i", a));
    PyTuple_SetItem(pArgs, 1, Py_BuildValue("i", b));
    PyObject* pRet = PyObject_CallObject(pFunction, pArgs);  // 调用函数
    
    int ans = 0;
    PyArg_Parse(pRet, "i", &ans);  // 解析返回值
    
    Py_DECREF(pModule);  // 释放对象
    Py_DECREF(pFunction);
    Py_DECREF(pArgs);
    Py_DECREF(pRet);
    Py_Finalize();  // 关闭Python解释器
    return 0;
}

要想执行成功,需要设置PYTHONPATH环境变量,可通过set命令在命令行窗口临时创建,也可通过系统设置永久环境变量:

posted @ 2024-07-22 02:01  songlh424  阅读(187)  评论(0)    收藏  举报