Note that there are some explanatory texts on larger screens.

plurals
  1. POVariable sized packet structs with vectors
    text
    copied!<p>Lately I've been diving into network programming, and I'm having some difficulty constructing a packet with a variable "data" property. Several prior questions have helped tremendously, but I'm still lacking some implementation details. I'm trying to avoid using variable sized arrays, and just use a vector. But I can't get it to be transmitted correctly, and I believe it's somewhere during serialization.</p> <p>Now for some code.</p> <p>Packet Header</p> <pre><code>class Packet { public: void* Serialize(); bool Deserialize(void *message); unsigned int sender_id; unsigned int sequence_number; std::vector&lt;char&gt; data; }; </code></pre> <p>Packet ImpL</p> <pre><code>typedef struct { unsigned int sender_id; unsigned int sequence_number; std::vector&lt;char&gt; data; } Packet; void* Packet::Serialize(int size) { Packet* p = (Packet *) malloc(8 + 30); p-&gt;sender_id = htonl(this-&gt;sender_id); p-&gt;sequence_number = htonl(this-&gt;sequence_number); p-&gt;data.assign(size,'&amp;'); //just for testing purposes } bool Packet::Deserialize(void *message) { Packet *s = (Packet*)message; this-&gt;sender_id = ntohl(s-&gt;sender_id); this-&gt;sequence_number = ntohl(s-&gt;sequence_number); this-&gt;data = s-&gt;data; } </code></pre> <p>During execution, I simply create a packet, assign it's members, and send/receive accordingly. The above methods are only responsible for serialization. Unfortunately, the <strong>data</strong> never gets transferred.</p> <p>Couple of things to point out here. I'm guessing the <strong>malloc</strong> is wrong, but I'm not sure how else to compute it (i.e. what other value it would be). Other than that, I'm unsure of the proper way to use a vector in this fashion, and would love for someone to show me how (code examples please!) :)</p> <p>Edit: I've awarded the question to the most comprehensive answer regarding the implementation with a vector data property. Appreciate all the responses!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload