2017-06-19 57 views
0

不知道這是我的錯誤還是誤解。任何幫助非常感謝。一個簡潔的項目演示這個問題是hereSWIG:numpy包裝的意外結果?

我正在包裝一些C++函數採取指針緩衝區(8位有符號或無符號)和一個int與緩衝區長度,通常遵循此模式:some_function(char * buffer ,INT長度)

採用的示例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)

我在哪裏出錯了? TAIA。

[UPDATE1]

%申請變更爲每柔印的建議

// 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 
+0

我真的不介意被低估,但_please_會有建設性?爲什麼這個研究不充分?陳述你的理由! –

回答

0

%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)} 
+0

謝謝,非常感謝。奇怪的是,這個問題修復了66%的問題,但是並不適用於普通的char *類型。我正在使用SWIG 4.0.0 –

+0

char *往往會有點特別,因爲你也會碰到字符串類型映射。 – Flexo

+0

時間SWIG然後硬着頭皮,並開始使用鏗鏘...感謝您的所有幫助。 –