简介:python调用dll
前提简要:在python调用动态库时,想要将动态二维数组作为输入输出参数。但是网上的教程绝大部分都是在声明时已经确定数组大小的静态数组,不符合实际使用的要求。此文章参考网友的写法,记录python调用dll时,传递动态二维数组的方法。
难点:传递二级指针
生成动态库
// add.h
#ifndef ADD_H
#define ADD_H
#ifdef __cplusplus
extern "C" {
#endif
_declspec(dllexport) void add(float** a, float** b, float** c, int rows, int cols);
#ifdef __cplusplus
}
#endif
#endif
// add.cpp
#include "add.h"
#ifdef __cplusplus
extern "C" {
#endif
void add(float** a, float** b, float** c, int rows, int cols) {
for (int ri = 0; ri < rows; ++ri) {
for (int ci = 0; ci < cols; ++ci) {
c[ri][ci] = a[ri][ci] + b[ri][ci];
}
}
}
#ifdef __cplusplus
}
#endif
详情见:生成动态库
python调用dll
将Add.dll 与 test_add.py 放在同一个目录下
from ctypes import *
import numpy as np
def myAdd(a,b):
add_dll=CDLL('.\\Add.dll')
(rows,cols)=a.shape
a_matrix=[]
b_matrix=[]
c_matrix=[]
for i in range(rows):
temp1=(c_float*cols)()
for j in range(cols):
temp1[j]=a[i][j]
a_matrix.append(cast(temp1,POINTER(c_float)))
temp2=(c_float*cols)()
for j in range(cols):
temp2[j]=b[i][j]
b_matrix.append(cast(temp2,POINTER(c_float)))
temp3=(c_float*cols)()
c_matrix.append(cast(temp3,POINTER(c_float)))
a_ptr=(POINTER(c_float)*rows)(*a_matrix)
b_ptr=(POINTER(c_float)*rows)(*b_matrix)
c_ptr=(POINTER(c_float)*rows)(*c_matrix)
add_dll.add(a_ptr,b_ptr,c_ptr,rows,cols)
c=np.zeros((rows,cols),dtype=float)
for i in range(rows):
for j in range(cols):
c[i][j]=c_ptr[i][j]
return c
if __name__ == "__main__":
a=np.linspace(1,15,15,dtype=float)
a=a.reshape(3,5)
b=np.ones((1,15),dtype=float)
b=b.reshape(3,5)
print('a=',a)
print('b=',b)
c=myAdd(a,b)
print('c=',c)
输出:
a= [[ 1. 2. 3. 4. 5.]
[ 6. 7. 8. 9. 10.]
[11. 12. 13. 14. 15.]]
b= [[1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1.]]
c= [[ 2. 3. 4. 5. 6.]
[ 7. 8. 9. 10. 11.]
[12. 13. 14. 15. 16.]]
代码
完整代码:C/C++、matlab、python:生成c动态库,matlab、python调用
不想使用积分下载的,可以私信邮箱,直接发你