Return vector<pair<int,int>> & from c++ method to python list of tuples using swig typemap

…衆ロ難τιáo~ 提交于 2019-12-04 07:29:05

A custom typemap is not necessary for this case. SWIG has built-in support for vector and pair templates, but you have to declare the pair template as well as the vector template:

%module x

%include <std_pair.i>
%include <std_vector.i>
%include <std_string.i>
%template() std::pair<int,int>;
%template(PairVector) std::vector<std::pair<int,int> >;

%{
#include "MyClass.h"
%}

%include "MyClass.h"

Example:

>>> import x
>>> a=x.PairVector(((1,2),(3,4),(5,6)))
>>> b=x.MyClass(a)
>>> b.GetMyVector()
((1, 2), (3, 4), (5, 6))

But note because your class is written to hold a reference to the passed-in vector and not a copy, you have to hold a reference to it for the lifetime of MyClass. For example:

>>> del a
>>> b.GetMyVector()
*Undefined Behavior (crash, empty vector, etc.)*
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!