Accessing 2 dimensional array from SWIG in Python

guhan balasubramanian <[email protected]> Mon, 28 Aug 2023 10:11:20 -0700
Newsgroups gmane.comp.programming.swig
Message-ID <CAMNAJg0P9h-XqjfRGh=o3niBD-z_nvD28u7A6WZAwN9qADhZeg@mail.gmail.com>
Hi,

I'm working on a SWIG layer to convert a C interface to Python.

*Problem:*
I have the following structure in C that I need to expose in Python:

C Code (example module):
// ==========================
typedef struct _myStruct {
  int x;
  int y;
} myStruct;

typedef struct _myData {
  int a[10][10];
  myStruct myS[10][10];
} myData;
// ==========================

With no special changes in the interface file, I'm able to receive a
populated myData variable. The problem I have is accessing it through
Python.

Python Code:
############################
import example as e
md = e.myData()
e.fill_data(md)

# The data for the 2 dimensional member variables are not subscriptable nor
iterable.
# md.a is of type "Swig object of type int (*)[10]"
# md.myS is of type "Swig object of type myData (*)[10]"
#############################

Could you please help with the pointers/existing-literature to access these
2-dimensional arrays? It would be a bonus if I could access the value in
the array as the same data type as in C. I am trying to avoid external
libraries like numpy or ctypes as much as possible.

*What I've tried so far:*
*Attempt 1: *
A typemap(out) for int [ROW_SIZE][COL_SIZE] or myData [ROW_SIZE][COL_SIZE].
There are two issues with this typemap:
- I need to pattern match with hardcoded ROW_SIZE/COL_SIZE since if I pass
ANY, it is hard to convert the data to a Python friendly format.
- The Python friendly format used was PyList [][] with PyLong elements as
values for int. So it should be straightforward for primitive data types.
- This solution gets complicated for custom structures like myStruct.

*Attempt 2:*
Tried in built functions in the interface file provided by SWIG, but this
is not able to convert the input type (Swig Object) to the corresponding
type defined by the array_functions.

%array_functions( int, intArray );
%pointer_class(int, intp);
%array_functions( intp, intpArray );
%pointer_functions(int, intpf);


Thanks,
Guhan

_______________________________________________
Swig-user mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/swig-user