Swig和多维数组 [英] Swig and multidimensional arrays
问题描述
我正在使用Swig将python与C代码进行接口.
I am using Swig to interface python with C code.
我想调用一个C函数,该函数将包含int ** var的结构作为参数:
I want to call a C function that takes for argument a struct containing an int** var:
typedef struct
{
(...)
int** my2Darray;
} myStruct;
void myCFunction( myStruct struct );
我正在努力处理多维数组.
I am struggling with multi dimensional arrays.
我的代码如下:
在界面文件中,我像这样使用carray:
In the interface file, I am using carray like this:
%include carrays.i
%array_class( int, intArray );
%array_class( intArray, intArrayArray );
在python中,我有:
In python, I have:
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 **'
我对行%array_class( intArray, intArrayArray )
表示怀疑.
我尝试对int*
使用typedef来创建数组,如下所示:
%array_class( myTypeDef, intArrayArray );
但这似乎没有用.
I doubt about the line %array_class( intArray, intArrayArray )
.
I tried using a typedef for int*
to create my array like this:
%array_class( myTypeDef, intArrayArray );
But it didn't seem to work.
您知道如何在Swig中处理多维数组吗?
Do you know how to handle multidimensional arrays in Swig ?
感谢您的帮助.
推荐答案
Have you considered using numpy for this? I have used numpy with my SWIG-wrapped C++ project for 1D, 2D, and 3D arrays of double and std::complex elements with a lot of success.
您需要获取numpy.i 并在您的python环境中安装numpy.
You would need to get numpy.i and install numpy in your python environment.
以下是您的结构示例:
.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)
这篇关于Swig和多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!