Link to home
Start Free TrialLog in
Avatar of ggets
ggets

asked on

mapping a Struct over a buffer problem

Hi, I used to do this is delphi all the time, but am just starting on C++..

I have a struct that i want to map over a buffer which is sent between the PC and a PIC over RS232. I guess im still a ltiile cofused over the different pointer types, but am getting an error 'Cannot convert from char(*)[200]  to pmsgHeader'

First I create a varible of a struct type :
pmsgHeader * header;

then try to point the variable to the buffer:
header = &buffer;

but this is the line that fails.

Thanks in advance,
Graeme

In My Header

typedef struct msgHeader
{
      unsigned char msgStart;
      unsigned short msgID;
      unsigned short dataLength;
      unsigned char msgEnd;
}pmsgHeader;


class msgTransport
{
private:
     char buffer[200];
public:
      msgTransport();
      ~msgTransport();
}
;


IN MY cpp file

msgTransport::msgTransport(){
      pmsgHeader *header;
      header = &buffer;
}
ASKER CERTIFIED SOLUTION
Avatar of nsanga
nsanga

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ggets
ggets

ASKER

Thanks,

First code example works a treat :-)
Second one seems to mess upi my buffer
Third one gives this error : error C2144: syntax error : 'char' should be preceded by ')'
on the "buffer=( char *) header ;" line.

But the first example is what I was looking for

Many Thanks
Avatar of evilrix
>> header =(pmsgHeader  *) buffer;
Actually, since this is C++ the correct way to do this is to use reinterpret_cast and NOT the deprecated and dangerous C-style cast.

header = reinterpret_cast<pmsgHeader  *>(buffer);

http://www.devx.com/tips/Tip/12504

Avatar of ggets

ASKER

Also works a treat, and I guess the more correct way of doing it.

First Solution still good as BoostC++ for the PIC devices does not have a "reinterpret_cast" command, so still very usefull for me.

Many Thanks
Graeme
>> First Solution still good
Yes the first solution correctly identifies your problem and if your C++ compiler doesn't support reinterpret_cast (although it's have to be old or specialist) it is a valid way to do this but it is not the preferred C++ way for the reasons I've stated. Anyway, as long as you have both ways you can now make an informed choice to do what suits your needs and that, of course, is the most important things.

Regards,

-Rx.
Avatar of ggets

ASKER

Hi evilrix,

I'm using two compilers. Visual C++ express for the Windows control App and BoostC++ for the PIC processor, which is, as you say, a specialist compiler. So I need both solutions.

Keeping track of all these languages (C, C#, C++, VB, Java, SQL) and their differences is a strain, but keeps me out of trouble , though sometimes i think  would prefer to be in trouble :-)

Thanks again for your input.
>> Thanks again for your input.
No worries, good luck my friend.