2012-01-27 103 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

相关问题