'What's the right way to send a multi dimensional array from a python script to a C++ code using NamedPipes?

I have a C++ code that expects a struct with this exact formate to be send to it through a NamedPipe:-

struct InputData {
  const std::array<std::array<float, 4>, 5> flexion;
  const std::array<float, 5> splay;
  const float joyX;
  const float joyY;
  const bool joyButton;
  const bool trgButton;
  const bool aButton;
  const bool bButton;
  const bool grab;
  const bool pinch;
  const bool menu;
  const bool calibrate;

  const float trgValue;
};

I am using a python script to extract this info and then packing it using the struct python library and send it to the C++ script:-

def encode(flexions, splay, joys, bools):
    
    if splay is None:
        splay = [0.0] * 5

    if joys is None:
        joys = [0.0] * 2

    if bools is None:
        bools = [False] * 8

    packed_flexions = struct.pack('@20f', *flexions)
    packed_splays = struct.pack('@5f', *splay)
    packed_joys = struct.pack('@2f', *joys)
    packed_bools = struct.pack('@8?', *bools)
    packed_padded = struct.pack('@f', 0.0)

    data = packed_flexions + packed_splays + packed_joys + packed_bools + packed_padded
    return data

The "flexion" variable is actually a 4×5 2D vector, and I have no idea how to send it through the struct library, so I flattened it (so now it's a 20 element python list) and packed it's elements one by one and send it but that raised an error in the C++ code.

So what I am doing wrong here? is the problem with the C++ script or my python implementation?

In the c++ code, the ReadFile function return 0 bytes afetr reading the message, so it receives it, but reads zeros bytes from it, I don't know why.



Solution 1:[1]

Ideally you should convert the c++ struct into a serializable form, like JSON or protocol buffers. This way, your python code can deserialize the data into a python friendly object.

Solution 2:[2]

After along time experimenting, the issue was from that I was initializing a new pipe connection every time I send a message to the pipe, so whatever you was sending n dimensions arrays, juts flatten it, this is the right way.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Missaka Wijekoon
Solution 2 AhmedAhmedEG2