c井语言python_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

// 注意指针的类型要与 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

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值