我正在尝试将 SWIG 包装(版本 3)int 到类指针的 C++ STL 映射到 Python 3:
示例.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;
}
};
示例.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>
而不是字典。它还有一个指向 map 的指针,而不是 map 。如何编写正确的 %typemap
将 STL 映射转换为 Python 3 字典?
我已经能够对例如以下 map 执行此操作int 到 int - 它是指向给我带来麻烦的类的指针。
谢谢。
最佳答案
让我从 SWIG 手册中为您获取相关条目... here
这告诉你成员变量 my_map
通过 SWIG 生成的 getter 进行访问,该 getter 返回 map<int,Test*> *
(或者引用,如果您给出 %naturalvar
指令)。因此,必须编写输出类型映射来处理 map<int,Test*> *
而不是map<int,Test*>
.
关于python - 用于指向类的指针的 STL 映射的 SWIG 类型映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42847258/