user3126089
user3126089

Reputation: 83

Struct conversion to raw char issue

I have following problem : There is my struct :

struct NET_CONNECTION_DISPATCH
{
    int len;
    int data_str_len;
    const char * data_str;
};

And here that struct is used :

const std::string dstr = "127.0.0.1 11001";
    ncd.len = 8 + dstr.length();
    ncd.data_str_len = dstr.length();
    ncd.data_str = dstr.c_str();

After that i want to send it by boost asio :

boost::asio::async_write(socket_, boost::asio::buffer((char*)&ncd, ncd.len),
      boost::bind(&Connection::handle_write, shared_from_this(),
        boost::asio::placeholders::error));

In received by client message everything is fine to 8 byte (header). String part of message is filled by random bytes. What I'm doing wrong ? I tried many options with always same result. Thanks.

Upvotes: 0

Views: 90

Answers (2)

diwatu
diwatu

Reputation: 5699

data_str in NET_CONNECTION_DISPATCH is a pointer, the value of data_str is just an 4 bytes memory address. when you use (char*)&ncd, the content of &ncd is just three ints. If you really want use that struct in that way, you should output data_str seperately.

boost::asio::async_write(socket_, boost::asio::buffer(ncd.data_str, ncd.len-8),
  boost::bind(&Connection::handle_write, shared_from_this(),
    boost::asio::placeholders::error));

Upvotes: 1

Roddy
Roddy

Reputation: 68043

The characters aren't 'in' your structure. The structure contains a pointer to them, and you're sending the pointer plus some extra random bytes following after the structure.

It looks like you're just trying to send a string (there's nothing else relevant in your structure) so you should do two writes: A 4-byte write of the string length, followed by an N-byte write of the actual string data.

Upvotes: 1

Related Questions