【发布时间】:2017-08-08 09:43:44
【问题描述】:
我正在尝试将 SWIG 包装(版本 3)一个 C++ STL 映射 int 到一个类的指针,到 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 = $1.begin(); iter != $1.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
返回
<Swig Object of type 'map< int,Test * > *' at 0x10135e7b0>
而不是字典。它还有一个指向地图的指针,而不是地图。如何编写正确的%typemap 以将 STL 映射转换为 Python 3 字典?
我已经能够为地图做到这一点,例如int 到 int - 它是一个给我带来麻烦的类的指针。
谢谢。
【问题讨论】:
标签: python c++ pointers stl swig