python - 用于指向类的指针的 STL 映射的 SWIG 类型映射

标签 python c++ pointers stl swig

我正在尝试将 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/

相关文章:

python - 无法更改 python 路径并配置 anaconda

python - API FedEx express "INVALID.INPUT.EXCEPTION","message":"Invalid field value in the input"

c++ - 如何调整结构元素数组的大小

c++ - 返回 char*/Visual Studio 调试器异常

javascript - 如何在 Python 中评估 javascript 代码

python - matplotlib 返回的最大 PSD 频率箱是否错误?

c++ - 试图从内存中删除字符串。不会让我分配给 cin

c++ - 为什么 C++14 通用 lambda 需要在参数规范中使用 auto?

c++ - 对象成员的迭代器 "pointing"

c - 段错误,malloc 字符指针