2012-01-27 59 views
8

我正在使用SWIG 2.0爲C++庫創建一個Python包裝器。一種方法的參數類型爲「const std :: map &」。 SWIG很高興地爲它生成一個包裝,但我無法弄清楚如何調用該方法。例如,如果我爲該參數傳遞{「a」:「b」},則會得到一個「NotImplementedError:錯誤的數字或參數類型爲重載函數」錯誤。SWIG如何在Python中包裝map <string,string>?

我看着生成的.cxx文件,希望它可以澄清,但它沒有。下面是處理該參數的代碼:

res4 = SWIG_ConvertPtr(obj3, &argp4, SWIGTYPE_p_std__mapT_std__string_std__string_t, 0 | 0); 
if (!SWIG_IsOK(res4)) { 
    SWIG_exception_fail(SWIG_ArgError(res4), "in method '" "new_Context" "', argument " "4"" of type '" "std::map< std::string,std::string > const &""'"); 
} 

它清楚地知道該參數存在,並且它應該是被轉換爲地圖的東西。但我無法弄清楚它真的需要我通過它。

+0

在你痛飲文件給你明確地包裹在地圖?我想你需要通過從python代碼中調用insert來創建一個填充類型的變量。 – mark 2012-01-27 23:22:45

回答

16

當您使用的是C++模板(如std::map<string, string>),你需要在你的.i文件爲它創建一個別名,所以你可以使用它在Python:

namespace std { 
%template(map_string_string) map<string, string>; 
} 

現在讓我們假設你想包裝的功能,看起來像這樣:

void foo(const std::map<string, string> &arg); 

在Python端,你需要傳遞一個map_string_string爲foo,而不是Python字典。事實證明,你可以很容易地轉換Python字典的地圖,雖然這樣做:如果你想調用foo

map_string_string({ 'a' : 'b' }) 

所以,你需要這樣做:

foo(map_string_string({ 'a' : 'b' })) 

下面是完整的例子代碼有效。

// test.i 
%module test 

%include "std_string.i" 
%include "std_map.i" 

namespace std { 
    %template(map_string_string) map<string, string>; 
} 

void foo(const std::map<std::string, std::string> &val); 

%{ 
#include <iostream> 
#include <string> 
#include <map> 

using namespace std; 
void 
foo(const map<string, string> &val) 
{ 
    map<string, string>::const_iterator i = val.begin(); 
    map<string, string>::const_iterator end = val.end(); 
    while (i != end) { 
     cout << i->first << " : " << i->second << endl; 
     ++i; 
    } 
} 

%} 

而且蟒蛇測試代碼:

#run_test.py 
import test 

x = test.map_string_string({ 'a' : 'b', 'c' : 'd' }) 
test.foo(x) 

我的命令行:

% swig -python -c++ test.i 
% g++ -fPIC -shared -I/usr/include/python2.7 -o _test.so test_wrap.cxx 
% python run_test.py 
a : b 
c : d 
+0

這不適用於我:map_string_string({'a':'b'})產生與{'a':'b'}完全相同的錯誤。我已經破解了生成的C++代碼,以獲取更多關於正在發生的事情的信息,而且這對我沒有任何意義。儘管我將一個字典(或map_string_string)傳遞給Python方法,但爲相應參數傳遞的PyObject是一個只包含鍵的元組。這些值似乎沒有被傳遞到任何地方。 – peastman 2012-01-28 01:07:02

+0

我添加了一個詳細的例子。試試看。 – 2012-01-28 20:27:09

+0

糟糕,我的錯。 (或者說,最初創建SWIG代碼的人的錯。)事實證明,有一些代碼預處理所有參數,這就是將字典轉換爲元組的原因。 – peastman 2012-01-30 18:44:23

相關問題