0

In my c++ extension i have a public method called: map getMap();

I have include the header files in to the Example.i interface file.

But how can i interate thru the map hwhen i am in python?

delita
  • 1,571
  • 1
  • 19
  • 25
  • See the answers on http://stackoverflow.com/questions/9041192/how-does-swig-wrap-a-mapstring-string-in-python for an example – Flexo Jan 29 '12 at 22:47

2 Answers2

2

Working example (Windows). An important point is you must instantiate each template you want to expose with the %template statement (see x.i file) and assign it a legal Python name.

x.cpp

#define X_EXPORTS
#include "x.h"

X_API mapii_t getMap()
{
    mapii_t m;
    m[1]=2;
    m[4]=8;
    m[5]=10;
    return m;
}

x.h

#pragma once

#ifdef X_EXPORTS
#define X_API __declspec(dllexport)
#else
#define X_API __declspec(dllimport)
#endif

#include <map>
typedef std::map<int,int> mapii_t;
X_API mapii_t getMap();

x.i

%module x

%{
    #include "x.h"
%}

// Let swig understand __declspec and other "window-isms"
%include <windows.i>
%include <std_map.i>

// instantiate template and give it a Pythonic name.
%template(mapii_t) std::map<int,int>;
%include "x.h"

makefile

_x.pyd: x_wrap.cxx x.dll
    cl /LD /W3 /MD /EHsc /IC:\Python27\include x_wrap.cxx -link /OUT:_x.pyd /libpath:C:\Python27\libs x.lib

x.dll: x.cpp
    cl /LD /W4 /MD /EHsc x.cpp

x_wrap.cxx: x.i
    swig -c++ -python x.i

Usage:

Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import x
>>> a=x.getMap()
>>> a
<x.mapii_t; proxy of <Swig Object of type 'std::map< int,int > *' at 0x022C4200> >
>>> for k,v in a.items():
...  print k,v
...
1 2
4 8
5 10
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
0

You should be able to use the map just like you would a python dict. It supports iteritems, iterkeys, etc. Do you have a %include "std_map.i" in your code? do you have a %template statement? It's pretty tough to guess since you didn't show your code.

Nathan Binkert
  • 8,744
  • 1
  • 29
  • 37