【问题标题】:How to convert (typemap) a jagged C++ vector of vectors to Python in SWIG如何在 SWIG 中将向量的锯齿状 C++ 向量转换(类型映射)为 Python
【发布时间】:2014-12-16 15:18:43
【问题描述】:

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

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

【问题讨论】:

    标签: python c++ swig


    【解决方案1】:

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

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

    【讨论】:

    • 包含矢量std::vector&lt;std::vector&lt;int, std::allocator&lt;int&gt;&gt;, std::allocator&lt;std::vector&lt;int, std::allocator&lt;int&gt;&gt;&amp;的完整模板定义可能更安全
    【解决方案2】:

    在 SWIG 中有内置支持,但它返回一个元组而不是一个列表。但是,这对您来说可能就足够了:

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

    结果:

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

    【讨论】:

    • 由于数据的大小,我们需要一个 Numpy 数组列表,但这可能适用于小型数据集
    猜你喜欢
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 2023-03-03
    • 2014-10-16
    • 2019-02-06
    • 2015-06-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多