1
我试图SWIG涡卷(版本3)INT的C++ STL地图一类的指针,到Python 3:SWIG类型映射为指针的STL地图一类
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 - 它是指向给我麻烦的类的指针。
谢谢。
谢谢!我想这是明显的答案。为什么getter会返回一个指针,而不是对象?例如,如果我们改为SWIG封装一个返回地图'map my_function();'的函数,那么SWIG将根据需要返回一个'map '而不是'map *'。 –
Kurt
getter返回一个指向成员对象的指针,以避免必须进行复制。如果它通过值返回,则会创建并返回成员对象的副本。这也在SWIG手册的上面链接中讨论过。 – m7thon
是有道理的 - 谢谢! – Kurt