gpt4 book ai didi

numpy - 在没有额外包装的情况下返回已知大小的向量?

转载 作者:行者123 更新时间:2023-12-02 03:42:59 24 4
gpt4 key购买 nike

我只是被 SWIG 和 numpy 的一个小问题困住了。我在 C 中有一个专门的矩阵 (n,k) 向量 (k) 乘积,我想将其连接到 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])

这很不方便。有没有办法在内部告诉 swig 大小?或者是提供用户友好界面以在其周围添加额外包装器的唯一方法:

def user_interface_mat_vec_mul(A,b):
mat_vec_mul(A,b,A.shape[0])

提前致谢。

最佳答案

这是我的答案,我找到了一种将包装函数放入 swig 文件的方法,它基本上可以满足我的要求:

%pythoncode %{
def mat_vec_mul(A, b):
return _test._mat_vec_mul(A, b, A.shape[0])
%}

关于numpy - 在没有额外包装的情况下返回已知大小的向量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18942097/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com