3
我只是被困在SWIG和numpy的小問題上。 我有一個專門的矩陣(n,k)矢量(k)產品在C中,我想要與numpy進行交互。所以我總是知道乘法之前輸出矢量(n)的形狀。返回已知大小的矢量而無需其他包裝?
目前,C函數分配內存並返回一個double *到計算產品。爲了防止存儲器泄漏和以避免改變C代碼 我在dot example接口,它像:
%apply (int DIM1, int DIM2, double* IN_ARRAY2) {(int m1, int nd1, double* xd)};
%apply (int DIM1, double* IN_ARRAY1) {(int nd2, double* zd)};
%apply (int DIM1, double* ARGOUT_ARRAY1) {(int nd4, double* za)};
%rename (mat_vec_mul) my_mat_vec_mul;
%ignore mat_vec_mul;
%include "math_lib.h"
%exception my_mat_vec_mul {
$action
if (PyErr_Occurred()) SWIG_fail;
}
%inline %{
void my_mat_vec_mul(int m1, int nd1, double* xd, int nd2, double* zd, int nd4, double* za)
{
if (nd1 != nd2) {
PyErr_Format(PyExc_ValueError,
"Arrays of lengths (%d,%d) given",
nd1, nd2);
}
int i;
double *tmp = NULL;
tmp = mat_vec_mul(m1,nd1,xd,zd);
for(i = 0; i < nd1; i++){
za[i] = tmp[i];
}
free(tmp);
}
%}
現在,因爲我指定輸出矢量作爲ARGOUT_ARRAY1,被調用的函數在Python作爲
v = test.mat_vec_mul(A,b,A.shape[0])
這是不方便的。有沒有辦法告訴內部大小?或者是提供用戶友好界面來添加附加包裝的唯一方式,如下所示:
def user_interface_mat_vec_mul(A,b):
mat_vec_mul(A,b,A.shape[0])
在此先感謝。