Swig和多维数组
我正在使用Swig将Cthon与C代码连接起来。
我想调用一个C函数,它接受一个包含int ** var的struct的参数:
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 )
我在myStruct.my2Darray = var上遇到错误:
TypeError: in method 'maStruct_monTableau2D_set', argument 2 of type 'int **'
我确实怀疑linge%array_class(intArray,intArrayArray)我尝试使用typedef for int *来创建我的数组:%array_class(myTypeDef,intArrayArray); 但它似乎没有用。
你知道如何处理Swig中的多维数组吗?
谢谢你的帮助。
你有没有考虑过使用numpy ? 我使用了我的SWIG包装的C ++项目的numpy,用于double和std :: complex元素的1D,2D和3D数组,并取得了很大的成功。
您需要获取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)
这就是我处理2d数组的方式。 我使用的技巧是编写一些内联代码来处理数组的创建和变异。 完成后,我可以使用这些function进行出价。
以下是示例代码。
ddarray.i
%module ddarray %inline %{ // Helper function to create a 2d array int* *int_array(int rows, int cols) { int i; int **arr = (int **)malloc(rows * sizeof(int *)); for (i=0; i
ddarray.c
int calculate(int **arr, int rows, int cols) { int i, j, sum = 0, product; for(i = 0; i < rows; i++) { product = 1; for(j = 0; j < cols; j++) product *= arr[i][j]; sum += product; } return sum; }
示例Python脚本
import ddarray a = ddarray.int_array(2, 3) for i in xrange(2): for j in xrange(3): ddarray.setitem(a, i, j, i + 1) print ddarray.calculate(a, 2, 3)