Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/344.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python SWIG:numpy包装的意外结果?_Python_C++_Numpy_Swig - Fatal编程技术网

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

Python SWIG:numpy包装的意外结果?,python,c++,numpy,swig,Python,C++,Numpy,Swig,不确定这是我的错误还是误解。非常感谢您的帮助。一个简明的项目演示了这个问题 我正在包装一些C++函数,这些函数使用一个指针(一个8位有符号或无符号)和一个带有缓冲长度的int,通常遵循这个模式:一些函数(char *缓冲,int长度)< /p> 采用该示例将基于以下内容生成外观正常的包装器: 例一: %module example %{ #define SWIG_FILE_WITH_INIT #include "example.h" %} // https://raw.git

不确定这是我的错误还是误解。非常感谢您的帮助。一个简明的项目演示了这个问题

我正在包装一些C++函数,这些函数使用一个指针(一个8位有符号或无符号)和一个带有缓冲长度的int,通常遵循这个模式:一些函数(char *缓冲,int长度)< /p> 采用该示例将基于以下内容生成外观正常的包装器:

例一:

%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"
例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
average_u8
现在按预期工作

但是,
双平均值_s8(字符*缓冲区,int字节)
仍然会失败

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
回溯(最近一次呼叫最后一次):
文件“test.py”,第25行,在
平均值=示例平均值(np)8
TypeError:average_s8需要2个参数,得到1个

您的
%apply
指令错误,与正在包装的功能不匹配:

%apply (int* INPLACE_ARRAY1, int DIM1) {(int* seq, int n)}
这与您的函数
average_i
不匹配,因为您给出的参数名称不同。更改SWIG看到的声明,即:

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

我真的不介意被否决,但请有建设性?为什么这方面的研究不足?陈述你的理由!谢谢,非常感谢。奇怪的是,这解决了约66%的问题,但对于普通的
char*
种类来说却没有。我用的是SWIG 4.0.0char*有点特别,因为你也碰到了字符串类型映射。现在是SWIG的时候了,你要咬紧牙关,开始使用Clang。。。谢谢你的帮助。
%apply (int* INPLACE_ARRAY1, int DIM1) {(int* buffer,int bytes)}