使用 numpy 和 swig 将二维数组作为参数传递给函数

Pass 2d array as argument to a function using numpy and swig

我正在尝试使用以下文件将 double 类型的 2D numpy 数组传递给函数 load_denseSPD_from_console。但我不断收到错误消息(见下文)

// "test.h"
SPDMATRIX_DENSE load_denseSPD_from_console(double* numpyArr,
                                           int row_numpyArr,
                                           int col_numpyArr);

// "test.cpp"
SPDMATRIX_DENSE load_denseSPD_from_console(double* numpyArr,
                                           int row_numpyArr,
                                           int col_numpyArr) {
  /* Load values of a numpy matrix `numpyArr` into a SPD matrix container
   
   @numpyArr: double pointer of type double

   @row_numpyArr: row of `numpyArr`

   @col_numpyArr: col of `numpyArr`

   @return: copy of a locally created SPD matrix which contains the values
            from `numpyArr`
  */
  SPDMATRIX_DENSE K(row_numpyArr, col_numpyArr);  // container for numpyArr

  // Fill the container
  int index = -1;
  for (int i = 0; i < row_numpyArr; i++)
    for (int j = 0; j < col_numpyArr; j++) {
      index = i * col_numpyArr + j;
      K.data()[index] = numpyArr[index];  // .data()'s type is double*
    }

  return K;
}


// "test.i"
%{
  #define SWIG_FILE_WITH_INIT
  #include "../example/test.cpp"
%}
%include "../example/test.cpp"

// Use numpy array
%include "numpy.i"
%init %{
  import_array();
%}


%apply (double* IN_ARRAY2, int DIM1, int DIM2 ) \
      {(double* numpyArr, int row_numpyArr, int col_numpyArr)};

这是我 运行

的 python 文件
# "test.py"

import test
import numpy as np

a = np.array([[2, -1, 0], [-1, 2, -1], [0, -1, 2]], dtype=np.double)

tools.load_denseSPD_from_console(a, 3, 3)
tools.load_denseSPD_from_console(a)

命令错误

test.load_denseSPD_from_console(a, 3, 3)

TypeError: in method 'load_denseSPD_from_console', argument 1 of type 'double *'

以及来自命令的错误

test.load_denseSPD_from_console(a)

TypeError: load_denseSPD_from_console() takes exactly 3 arguments (1 given)

我查了其他帖子Swig and multidimensional arrays,但我不知道哪里错了。

%include "../example/test.cpp"test.i 文件的最后一行,因此首先处理 %include "numpy.i" 和 %apply。如果没有首先处理类型映射(通过 %apply),那么在处理您的函数时将不会使用类型映射的代码。这就是为什么您看到的错误需要 3 个参数而不是 1 个...未应用将单个 numpy 数组参数转换为三个 C 参数的类型映射。

此外,您可以只 %include "../example/test.h" 而不是 .cpp。不需要实际代码,只需要声明。