2013-03-03 129 views
8

我有一個C++函數,其中給出了兩個參數,如下例所示。如何在Python + SWIG中接收引用和指針參數?

void func(int& n, char** data) 
{ 
    *data = other_func1(); // returns a char array 
    n = other_func2(); // returns the length of the array 
} 

我可以很容易地使用C或C++這個功能,但我不知道我怎樣才能從SWIG生成的Python模塊調用它。我想我將不得不編寫另一個C++函數,它返回,例如,std :: pair。但是如果可能的話,我想知道Python方面的解決方法。誰能幫忙?

回答

8

對於相當多的情況下(例如int *n)的這將是足夠的寫:

%apply int *OUTPUT { int *n }; 

其使用一些默認typemaps該SWIG提供輸出參數。 (INOUT和INPUT也是相似的)。

在這個例子中,儘管我們並不完全匹配任何預定義的情況,所以我們需要手動執行相同的操作。這基本上是每個參數兩個類型映射 - 一個輸入類型映射,它爲實際的函數調用創建臨時的東西,並使用它來代替一些實際的輸入和一個將臨時結果歸還Python的argout。在Python的情況下,使用元組來返回多個參數是有意義的。

一個例子:

%module test 

%typemap(in,numinputs=0) int& n (int temp) "$1 = &temp;" 
%typemap(in,numinputs=0) char **data (char *temp) "$1 = &temp;" 

%typemap(argout) char **data { 
    %append_output(PyString_FromString(*$1)); 
} 

%typemap(argout) int& n { 
    %append_output(PyInt_FromLong(*$1)); 
} 

%inline %{ 
    void foo(int& n, char **data) { 
    static char str[] = "Hello world"; 
    *data = str; 
    n = sizeof str; 
    } 
%} 

注意要點:

臨時變量(int tempchar *temp)自動獲得改名停靠明顯的名稱衝突。 %append_output是一個SWIG宏,它擴展到在Python中添加一些元素到$result元組後面。如果你的函數foo是動態分配的內存,你需要處理它。如果intypemap需要動態分配內存,freearg typemap通常很有用。

這足以讓我編譯並運行它想:

import test 

len,str = test.foo() 

print len 
print str