我使用swig将python与c代码接口。
我想调用一个c函数,它接受一个包含int**var的结构作为参数:

typedef struct
{
    (...)
    int** my2Darray;
} myStruct;

void myCFunction( myStruct struct );

我在和多维数组做斗争。
我的代码如下:
在接口文件中,我使用carray如下:
%include carrays.i
%array_class( int, intArray );
%array_class( intArray, intArrayArray );

在python中,我有:
myStruct = myModule.myStruct()
var = myModule.intArrayArray(28)

for j in range(28):
    var1 = myModule.intArray(28)

    for i in range(28):
        var1[i] = (...) filling var1 (...)

    var[j] = var1

myStruct.my2Darray = var

myCFonction( myStruct )

我在线路上发现一个错误:
TypeError: in method 'maStruct_monTableau2D_set', argument 2 of type 'int **'

我怀疑这条线。
我尝试使用typedef formyStruct.my2Darray = var创建我的数组,如下所示:
%array_class( intArray, intArrayArray )
但似乎没用。
你知道如何在swig中处理多维数组吗?
谢谢你的帮助。

最佳答案

你考虑过用numpy来做这个吗?我已经用NoMIP和我的Sigg包裹C++项目来做一个二维、STD:1D、2D和3D数组:复杂的元素,取得了很大的成功。
您需要get numpy.i并在python环境中安装numpy。
下面是一个如何构建它的示例:
.I文件:

// Numpy Related Includes:
%{
#define SWIG_FILE_WITH_INIT
%}
// numpy arrays
%include "numpy.i"
%init %{
import_array(); // This is essential. We will get a crash in Python without it.
%}
// These names must exactly match the function declaration.
%apply (int* INPLACE_ARRAY2, int DIM1, int DIM2) \
      {(int* npyArray2D, int npyLength1D, int npyLength2D)}

%include "yourheader.h"

%clear (int* npyArray2D, int npyLength1D, int npyLength2D);

.h文件:
/// Get the data in a 2D Array.
void arrayFunction(int* npyArray2D, int npyLength1D, int npyLength2D);

.cpp文件:
void arrayFunction(int* npyArray2D, int npyLength1D, int npyLength2D)
{
    for(int i = 0; i < npyLength1D; ++i)
    {
        for(int j = 0; j < npyLength2D; ++j)
        {
            int nIndexJ = i * npyLength2D + j;
            // operate on array
            npyArray2D[nIndexJ];
        }
    }
}

.py文件:
def makeArray(rows, cols):
    return numpy.array(numpy.zeros(shape=(rows, cols)), dtype=numpy.int)

arr2D = makeArray(28, 28)
myModule.arrayFunction(arr2D)

08-24 16:58
查看更多