3

我想使用输入双数组和整数数组的 SWIG 将 c++ 函数传递给 python。有没有办法做到这一点?

例如,我有一个接受 double 和 int 数组的 c++ 函数:

double myfun(double* a, int n, int* b, int m){...}

在 SWIG 接口文件中,我尝试编写

%apply (double* IN_ARRAY1, int DIM1, int* IN_ARRAY1, int DIM1) {(double* a, int n, int* b, int m)}

但没有运气。它编译了,但我不能像在 python 中调用 myfun 函数一样

myfun(a,b) 

其中 a 是双 numpy 数组, b 是整数 numpy 数组。我在python中收到以下错误:

myfun() takes exactly 4 arguments (2 given)

有什么建议么?这甚至可能吗?

谢谢!

4

1 回答 1

1

简短的回答是您需要使用一个接受两个输入但将 numinputs 属性设置为 1 的类型映射,例如:

%module test

%typemap(in,numinputs=1) (double *a, size_t) %{
  assert(PyList_Check($input));
  $2 = PyList_Size($input);
  $1 = malloc(sizeof *$1 * $2);
  for(size_t i = 0; i < $2; ++i) {
    $1[i] = PyFloat_AsDouble(PyList_GetItem($input, i));
  }
%}

%typemap(in, numinputs=1) (int *b, size_t) %{
  assert(PyList_Check($input));
  $2 = PyList_Size($input);
  $1 = malloc(sizeof *$1 * $2);
  for (size_t i = 0; i < $2; ++i) {
    $1[i] = PyInt_AsLong(PyList_GetItem($input, i));
  }
%}

%typemap(freearg) (double *a, size_t) %{
  free($1);
%}

%typemap(freearg) (int *b, size_t) %{
  free($1);
%}

%inline %{
  double myfun(double *a, size_t n, int *b, size_t m) {
    (void)a; (void) b;
    printf("%d, %d\n", n, m);
    for (size_t i = 0; i < (n > m ? n : m); ++i) {
      printf("%d: %f - %d\n", i, i < n ? a[i] : 0, i < m ? b[i] : 0);
    }
    return 1.0;
  }
%}

这行得通,每对 (array, len) 都有一个类型映射,足以用作:

import test

a = [0.5, 1.0, 1.5]
b = [1,2,3]

test.myfun(a,b)

我们本可以使用allocaC99 的 VLA 功能来避免malloc调用,但出于说明目的,这是可行的。

(注意:你没有const在函数原型中写过任何地方,但这意味着它没有修改输入数组。如果不是这种情况,那么你需要编写一个相应的 argout 类型映射以从分配的数组中复制,返回进入 Python 列表)。

然而,它也是相当重复的,所以如果我们可以在两者之间共享一些代码可能会更好——如果需要,你可以使用一些更高级的 SWIG 功能来做到这一点。如果需要,您还可以添加对内存视图的支持作为输入,而不仅仅是列表。

于 2013-07-14T14:19:37.290 回答