Skip to content

Reading c++ 2d array in python swig

An answer to this question on Stack Overflow.

Question

C++ part I have a class a with a public variable 2d int array b that I want to print out in python.(The way I want to access it is a.b)

I have been able to wrap the most part of the code and I can call most of the functions in class a in python now.

So how can I read b in python? How to read it into an numpy array with numpy.i(I find some solution on how to work with a function not variable)? Is there a way I can read any array in the c++ library? Or I have to deal with each of the variables in the interface file.

for now b is <Swig Object of type 'int (*)[24]' at 0x02F65158> when I try to use it in python

ps:

  1. If possible I don't want to modify the cpp part.

  2. I'm trying to access a variable, not a function.

So don't refer me to links that doesn't really answer my question, thanks.

Answer

You'll find that passing things back and forth between languages is much easier if you use a one-dimensional array in which you access elements using, e.g. arr[y*WIDTH+x].

Since you are operating in C++ you can even wrap these arrays in classes with nice operator()(int x, int y) methods for use on the C++ side.

In fact, this is the internal representation which Numpy uses for arrays: they are all one-dimensional.