2013-11-27 16 views
0

(我重新措辭的問題用一個例子,所以它也許更清楚我想要什麼)我可以在SWIG翻譯方法時推導出一些C++參數嗎?

說我有一個C++函數:

void foobar(int arg0, int arg1); 

我想痛飲翻譯成Python 。但是,在Python中,我只想使用參數arg1,並且計算arg0是相同的。換句話說,我想讓它這樣Python

>>>foobar(x) 

相當於C++

foobar(x, x); 

任何整數x。怎麼樣?

亞歷克斯的答案是指向某個方向,但還不夠遠。特別是

%typemap(in, numinputs=0) int arg0 { 
} 

是非常有用的,它允許我傳遞1個參數,Python不會抱怨。好。但是,剩下的部分是,如何從arg1在一個typemap中計算arg0

回答

1

使用multi-argument typemap。請注意,typemap將匹配任何在其參數列表中具有參數集的函數。這是最經常用於映射Python字符串到雙用C參數,如char*, size_t,但可用於每當一個Python參數可以被映射到多個參數:

%module x 

// for a single input parameter in Python, if a function takes two integers 
// named explicitly "int arg0, int arg1", map the two parameters to that 
// same input. 
%typemap(in) (int arg0, int arg1) %{ 
    $1 = PyInt_AsLong($input); 
    $2 = $1; 
%} 

%inline %{ 
#include <stdio.h> 
void foo(int arg0, int arg1) 
{ 
    printf("%d %d\n",arg0,arg1); 
} 
void bar(int arg0, int arg1, int other) 
{ 
    printf("%d %d %d\n",arg0,arg1,other); 
} 
void baz(int other, int arg0, int arg1) 
{ 
    printf("%d %d %d\n",other,arg0,arg1); 
} 
%} 

輸出:

>>> import x 
>>> x.foo(5) 
5 5 
>>> x.bar(1,5) 
1 1 5 
>>> x.baz(5,1) 
5 1 1 
1

您可以使用inargout typemap類型。它們的主要目的是允許在其他參數中返回多個值。但副作用是隱藏在目標語言的參數:

%typemap(in, numinputs=0, noblock=1) type1 *arg1 { 
    type1 arg1; 
    $1 = &arg1; 
} 

%typemap(argout) type1 *arg1 { 
    // now *$1 has the value of Py_calculate_value_of_arg1() 
    // you can do additional checks here 
} 

returnType foobar(type0 arg0, type1 *arg1) { 
    *arg1 = Py_calculate_value_of_arg1(); 
} 

的Python代碼將

foobar(arg0_value) 

請參閱該文檔http://www.swig.org/Doc2.0/Python.html#Python_nn61

+0

是的,我剛剛嘗試你的第一個答案,沒有工作,讓我試一下你的編輯後,謝謝 –

+0

是的,我錯過了'typemap(in)'。對於參考你看到https://sourceforge.net/p/cmusphinx/code/HEAD/tree/trunk/sphinxbase/swig/typemaps.i我用上面的把戲把C風格的錯誤代碼變成例外。 –

相關問題