SWIG:numpy 包装器的意外结果?

SWIG: Unexpected results with numpy wrappers?

不确定这是错误还是我的误解。非常感谢任何帮助。演示该问题的简明项目是 here

我正在包装一些 C++ 函数,这些函数采用指向缓冲区(8 位有符号或无符号)的指针和具有缓冲区长度的 int,通常遵循以下模式:some_function(char* buffer,int length )

采用示例 here 根据以下内容生成外观合理的包装器:

example.i:

%module example

%{
    #define SWIG_FILE_WITH_INIT
    #include "example.h"
%}

// https://raw.githubusercontent.com/numpy/numpy/master/tools/swig/numpy.i
%include "numpy.i"

%init %{
    import_array();
%}

//
%apply (char* INPLACE_ARRAY1, int DIM1) {(char* seq, int n)}
%apply (unsigned char* INPLACE_ARRAY1, int DIM1) {(unsigned char* seq, int n)}
%apply (int* INPLACE_ARRAY1, int DIM1) {(int* seq, int n)}

// Include the header file with above prototypes
%include "example.h"

example.h:

// stubbed
double average_i(int* buffer,int bytes)
{
    return 0.0;
}

但是运行这个测试:

np_i = np.array([0, 2, 4, 6], dtype=np.int)
try:
    avg = example.average_i(np_i)
except Exception:
    traceback.print_exc(file=sys.stdout)
try:
    avg = example.average_i(np_i.data,np_i.size)
except Exception:
    traceback.print_exc(file=sys.stdout)

产生错误:

Traceback (most recent call last):
  File "test.py", line 13, in <module>
    avg = example.average_i(np_i)
TypeError: average_i expected 2 arguments, got 1
Traceback (most recent call last):
  File "test.py", line 17, in <module>
    avg = example.average_i(np_i.data,np_i.size)
TypeError: in method 'average_i', argument 1 of type 'int *'

第一个有道理,但与食谱中的示例相反。第二个虽然没有,average_i的签名是double average_i(int* buffer,int bytes)

我哪里错了?泰亚

[更新1]

%apply 定义已根据 Flexo 的建议进行了更改

// integer
%apply (int* INPLACE_ARRAY1,int DIM1) {(int* buffer,int bytes)}
// signed 8
%apply (char* INPLACE_ARRAY1,int DIM1) {(char* buffer,int bytes)}
// unsigned 8
%apply (unsigned char* INPLACE_ARRAY1,int DIM1) {(unsigned char* buffer,int bytes)}

函数 average_iaverage_u8 现在可以正常工作了。

然而 double average_s8(char* buffer,int bytes) 仍然失败

Traceback (most recent call last):
  File "test.py", line 25, in <module>
    avg = example.average_s8(np_i8)
TypeError: average_s8 expected 2 arguments, got 1

您的 %apply 指令是错误的,与您包装的函数不匹配:

%apply (int* INPLACE_ARRAY1, int DIM1) {(int* seq, int n)}

这与您的函数不匹配average_i,因为您提供的参数名称不同。更改您的 %apply to match SWIG 看到的声明,即:

%apply (int* INPLACE_ARRAY1, int DIM1) {(int* buffer,int bytes)}