如何使用 swig 将 c++ int** return 值类型映射到 python

how to typemap c++ int** return value to python with swig

下面是我的代码:

int** myfunction()
{
    int **value = new int*[4];
    for(int i=0;i<4;i++)
    {
        value[i] = new int[4];
        memset(value[i], 0, 4*sizeof(int));
    }
    // asign value

    return value;
}

然后我想调用 myfunction 并使用 python 列表返回 int ** 类型值,所以我在我的 .i 文件中添加了一个类型映射:

%typemap(out) int** {
    $result = PyList_New(4);
    for(int i=0;i<4;i++)
    {
        PyObject *o = PyList_New(4);
        for(int j=0;j<4;j++)
        {
            PyList_SetItem(o,j,PyInt_FromLong((long)[i][j]));
        }
        PyList_SetItem($result, i, o);
    }
    delete ;
}

我在我的 python 代码中调用了 myfunction 但没有得到任何结果。我的代码有什么不正确的地方?

除了内存泄漏(只删除了外部 new 而不是内部的),您的代码看起来没问题。这是我所做的:

test.i

%module test

%typemap(out) int** {
    $result = PyList_New(4);
    for(int i=0;i<4;i++)
    {
        PyObject *o = PyList_New(4);
        for(int j=0;j<4;j++)
        {
            PyList_SetItem(o,j,PyInt_FromLong((long)[i][j]));
        }
        delete [] [i];
        PyList_SetItem($result, i, o);
    }
    delete [] ;
}

%inline %{
int** myfunction()
{
    int **value = new int*[4];
    for(int i=0;i<4;i++)
    {
        value[i] = new int[4];
        for(int j=0;j<4;j++)
            value[i][j] = i*4+j;
    }

    return value;
}
%}

使用 SWIG 和 VS2015 编译器构建:

swig -c++ -python test.i
cl /EHsc /LD /W3 /MD /Fe_test.pyd /Ic:\python36\include test_wrap.cxx -link /libpath:c:\python36\libs

输出:

>>> import test
>>> test.myfunction()
[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]]