//demo.c
#include <stdio.h>
#include <stdlib.h>
void fn2(void *p,void *o,int length)
{
u_char *p_new = (u_char *)p;
u_char *o_new =(u_char *)o;
for (int i=0;i<length;i++)
{
u_char data = p_new[i];//*(u_char *)p++;
o_new[i]=data+100;
}
}
gcc -o demo.so -std=c++11 -shared -fPIC demo.c
//main.py
import ctypes as ct
import time
def test_demo2():
m = np.arange(10,dtype=np.uint8)
print("Origin input:",m)
so = ct.cdll.LoadLibrary("./demo.so")
p = m.ctypes.data_as(ct.POINTER(ct.c_void_p))
out_array = np.empty(m.shape,dtype=np.uint8)
print("Origin output:",out_array)
q = out_array.ctypes.data_as(ct.POINTER(ct.c_void_p))
so.fn2(p,q, len(m))
print("=================================")
print("Output Result:",out_array)
if __name__ == '__main__':
test_demo2()
python3 main.py
Origin input: [0 1 2 3 4 5 6 7 8 9]
Origin output: [ 0 141 43 235 57 127 0 0 0 141]
=================================
Output Result: [100 101 102 103 104 105 106 107 108 109]
概述:
示例实现了numpy数组加上100并通过另外的数组的指针获取返回值。主要过程是
numpy数组转换成c_void_p类型,然后传参给c语言函数,c语言函数中指针强转到需要的数据类型,然后再处理。这样即可改变numpy数组中的数值实现各种计算。文章来源:https://www.toymoban.com/news/detail-651602.html
该方法可以实现python一些算子的速度优化(有无因患要后续确认)文章来源地址https://www.toymoban.com/news/detail-651602.html
到了这里,关于python通过ctypes传参numpy给c语言函数的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!