Loading

Python 调用 C 语言(使用 C 函数处理 NumPy 数据)

Python 调用 C 函数

python 调用 c 函数来实现两个整型数相加;

  • c 代码
// adder.c
// gcc -shared -Wl,-soname,adder -o adder.so -fPIC adder.c

int add(int x, int y)
{
    return x + y;
}
  • python 代码
# test.py
# python3 test.py

from ctypes import CDLL

adder = CDLL('./adder.so')
print(adder.add(99, 1))

使用命令 gcc -shared -Wl,-soname,adder -o adder.so -fPIC adder.c 对源程序进行编译得到链接库文件,再运行 python 程序调用链接库。

C 函数处理 NumPy 数据

python 调用 c 函数实现计算 numpy 矩阵各个元素的总和;

  • c 代码
// matrix.c
// gcc -shared -Wl,-soname,matrix -o matrix.so -fPIC matrix.c

#include <stdio.h>

// 注意指针的类型要与 numpy 定义时的类型位宽一致
int sum(int *mat, int w, int h)
{
    int i, j;
    int t = 0;
    for (i = 0; i < h; i++)
        for (j = 0; j < w; j++)
            t += mat[i * w + j];
    return t;
}
  • python 代码
# test.py
# python3 test.py

import numpy as np
from ctypes import CDLL, cast, POINTER, c_int32

matrix = CDLL('./matrix.so')

mat = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int32)
print('mat:\n', mat)

# 使 numpy 矩阵中的元素在内存中连续分布,便于 c 访问
if not mat.flags['C_CONTIGUOUS']:
    mat = np.ascontiguous(mat, dtype=mat.dtype)
# 获取矩阵的指针
mat_ctypes_ptr = cast(mat.ctypes.data, POINTER(c_int32))

sum = matrix.sum(mat_ctypes_ptr, 3, 2)
print('sum:', sum)

同样使用命令 gcc -shared -Wl,-soname,matrix -o matrix.so -fPIC matrix.c 对源程序进行编译得到链接库文件,再运行 python 程序调用链接库,输出结果如下:

mat:
 [[1 2 3]
 [4 5 6]]
sum: 21
posted @ 2021-01-19 12:38  循环展开  阅读(522)  评论(1编辑  收藏  举报