Python std::array type inside C++ class

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
Report Content as Inappropriate

Python std::array type inside C++ class

Guillaume Bittoun
Hello everyone,

I am pretty new to SWIG and have problem converting C++ types to Python
types (nevertheless this tool is awesome, it spares me precious hours
and does a very good job).

My problem is that I wanted to retrieve C++ array as Python tuples. This
problem seemed pretty easy to solve when having a quick look on the
internet, the solution was to add this in my *.i file :

%include std_array.i

namespace std {
     %template(Mat4) array<array<float, 4>, 4>; //Matrix type becomes 4D
tuple of tuple ((w, x, y, z), (…), (…), (…))
     %template(Vec2) array<float, 2>; // 2D vector type becomes 2D tuple
(x, y)
     %template(Vec3) array<float, 3>; // 3D vector type becomes 3D tuple
(x, y, z)

Everything went fine on the python side (ie. array<float, N> where
converted to tuples in python) until I create a struct type that uses
these array types :

struct Vertex
     std::array<float, 3> position;
     std::array<float, 3> normal;
     std::array<float, 4> color;

With that, when retrieving a Vertex in the python code, this is what I get :

In [1]: import MyLibPython

In [2]: v = MyLibPython.Vertex()

In [3]: v
Out[3]: <MyLibPython.Vertex; proxy of <Swig Object of type 'Vertex *' at
0x10e071930> >

In [4]: v.position
Out[4]: <MyLibPython.Vec3; proxy of <Swig Object of type 'std::array<
float,3 > *' at 0x10e08e0c0> >

In [5]: v.position = (1, 2, 3)
TypeError                                 Traceback (most recent call last)
<ipython-input-5-467605a76185> in <module>()
----> 1 v.position = (1, 2, 3)

<more traceback>…

As you can see, inside my struct, when querying for the position, the
output type is not as simple as a tuple, and I sadly cannot set the
position (nor the other attributes) with tuples, the type inside my
struct becomes way more complicated to get and set (thankfully, a cast
like `tuple(v.position)` converts the type to tuple instantly). This
problem seems limited to types inside a struct as I return
std::array<float, 3> in other parts of my code and gets converted as
tuple in the python code right away, no tricks needed. I already thought
about changing C++ attributes to C++ accessors (like getPosition(),
getNormal() etc…) but I’d like to be sure there is no other option
before changing my code.

could anyone tell me if there is a way to make SWIG consider these
array<float, N> as tuples inside when getting/setting the struct
attributes ? Or a workaround ?

I wonder if I’m asking too much to SWIG, but any suggestion is welcome.



Check out the vibrant tech community on one of the world's most
engaging tech sites, SlashDot.org! http://sdm.link/slashdot
Swig-user mailing list
[hidden email]