如何在SWIG中将矢量的锯齿状C ++向量转换(typemap)到Python

How to convert (typemap) a jagged C++ vector of vectors to Python in SWIG

将向量返回类型的锯齿形C++向量转换为Python列表的SWIG类型映射是什么?

1
std::vector<std::vector<int>>


在bindings.i文件中,放置以下类型映射:

1
2
3
4
5
6
7
8
9
10
%typemap(out) std::vector<std::vector<int>>&
{
    for(int i = 0; i < $1->size(); ++i)
    {      
        int subLength = $1->data()[i].size();
        npy_intp dims[] = { subLength };
        PyObject* temp = PyArray_SimpleNewFromData(1, dims, NPY_INT, $1->data()[i].data());
        $result = SWIG_Python_AppendOutput($result, temp);
    }      
}


swig中有内置支持,但它返回的是元组而不是列表。但是,这对您来说可能已经足够了:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
%module test

%{
    #include <vector>
%}

%include <std_vector.i>                      // built-in support
%template() std::vector<int>;                // declare instances of templates used to SWIG.
%template() std::vector<std::vector<int> >;

%inline %{                                   // Example code.
std::vector<std::vector<int> > func()
{
    std::vector<std::vector<int> > vv;
    std::vector<int> v;
    v.push_back(1);
    v.push_back(2);
    v.push_back(3);
    vv.push_back(v);
    v.clear();
    v.push_back(4);
    v.push_back(5);
    vv.push_back(v);
    return vv;
}
%}

结果:

1
2
3
>>> import test
>>> test.func()
((1, 2, 3), (4, 5))