Raj
Raj

Reputation: 273

buffer to struct conversion

I'm trying to convert a string to a structure.the struct in first field stores number of chars present in second field. Please let me know what I'm missing in this program. I'm getting output wrongly(some big integer value)

update: Can this program be corrected to print 4 (nsize) ?

#include <iostream>
using namespace std;

struct SData
{
    int nsize;
    char* str;
};

void main()
{
    void* buffer = "4ABCD";

    SData *obj = reinterpret_cast< SData*>(buffer);

    cout<<obj->nsize;
}

Upvotes: 0

Views: 140

Answers (3)

pm100
pm100

Reputation: 50120

if you want to make an ASCII representation of a piece of data then , yes, you need to do serialization. This is not simply a matter of hoping that a human readable version of what you think of as the contents of a struct can simply be cast to that data. You have to choose a serialization format then either write code to do it or use an existing library.

Popular Choices:

  • xml
  • json
  • yaml

I would use json - google for "c++ json library"

Upvotes: 1

Slava
Slava

Reputation: 44238

Your approach is utterly wrong. First of all binary representation of integer depends on platform, ie sizeof of int and endiannes of hardware. Second, you will not be able to populate char pointer this way, so you need to create some marshalling code that reads bytes according to format, convert them to int and then allocate memory and copy the rest there. Simple approach with casting block of memory to your struct will not work with this structure.

Upvotes: 3

Donghui Zhang
Donghui Zhang

Reputation: 1133

In an SData object, an integer occupies four bytes. Your buffer uses one byte. Further, a character '4' is different from a binary form of an integer 4.

Upvotes: 1

Related Questions