指向 class 的指针的 STL 映射的 SWIG 类型映射

SWIG typemap for STL map of pointers to a class

我正在尝试将 SWIG 包装(版本 3)int 的 C++ STL 映射到 class 的指针,到 Python 3:

example.h

#include <map>

using namespace std;

class Test{};

class Example{
public:
    map<int,Test*> my_map;
    Example() 
    {
        int a=0;
        Test *b = new Test();
        this->my_map[a] = b;
    }
};

example.i

%module example

%{
     #include "example.h"
%}

using namespace std;

%typemap(out) map<int,Test*> {
  $result = PyDict_New();

  map<int,Test*>::iterator iter;
  Test* theVal;
  int theKey;

  for (iter = .begin(); iter != .end(); ++iter) {
    theKey = iter->first;
    theVal = iter->second;
    PyObject *value = SWIG_NewPointerObj(SWIG_as_voidptr(theVal), SWIGTYPE_p_Test, 0);
    PyDict_SetItem($result, PyInt_FromLong(theKey), value);
  }
};

class Test{};

class Example{
public:
  map<int,Test*> my_map;
};

没有错误,但现在在 Python 3,运行

import example
t = example.Example()
t.my_map

returns

<Swig Object of type 'map< int,Test * > *' at 0x10135e7b0>

而不是字典。它还有一个指向地图的指针,而不是地图。如何编写正确的 %typemap 将 STL 映射转换为 Python 3 字典?

我已经能够对地图等进行此操作。 int 到 int - 它是指向 class 的指针给我带来了麻烦。

谢谢。

让我为您从 SWIG 手册中获取相关条目...here

这告诉您成员变量 my_map 是通过 SWIG 生成的 getter 访问的,其中 returns 是 map<int,Test*> * (或引用,如果您提供%naturalvar 指令)。因此,必须编写您的输出类型映射来处理 map<int,Test*> * 而不是 map<int,Test*>.