【问题标题】:SWIG typemap for STL map of pointers to a class用于指向类的指针的 STL 映射的 SWIG 类型映射
【发布时间】: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


    【解决方案1】:

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

    这告诉您成员变量 my_map 是通过 SWIG 生成的 getter 访问的,该 getter 返回 map&lt;int,Test*&gt; *(或引用,如果您提供 %naturalvar 指令)。因此,您的输出类型映射必须编写为处理 map&lt;int,Test*&gt; * 而不是 map&lt;int,Test*&gt;

    【讨论】:

    • 谢谢!我想这是显而易见的答案。为什么 getter 返回的是指针,而不是对象?例如,如果我们改为 SWIG 包装一个返回映射 map&lt;int,Test*&gt; my_function(); 的函数,则 SWIG 将根据需要返回 map&lt;int,Test*&gt; 而不是 map&lt;int,Test*&gt;*
    • getter 返回一个指向成员对象的指针以避免复制。如果它改为按值返回,则将制作并返回成员对象的副本。上述链接下的 SWIG 手册中也对此进行了讨论。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-04
    • 1970-01-01
    • 2017-12-20
    • 2011-01-09
    • 1970-01-01
    • 2012-09-09
    相关资源
    最近更新 更多