简体   繁体   中英

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

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

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

In the bindings .i file, put the following typemap:

%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);
    }       
}

There is built-in support in SWIG, but it returns a tuple instead of a list. It may be sufficient for you, however:

%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;
}
%}

Result:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM