2

I am working with a binary file structure. The code example for reading the data is in C, and I need to read it in Delphi. I hasten to add I have no C programming experience.

Given the following

typedef struct {
uchar ID, DataSource;
ushort ChecksumOffset;
uchar Spare, NDataTypes;
ushort Offset [256];
} HeaderType; 

...

typedef struct {
ushort ID;
...
ushort DistanceToBin1Middle,TransmitLength;
} FixLeaderType;

...

HeaderType *HdrPtr;
FixLeaderType *FLdrPtr;

unsigned char RcvBuff[8192];
void DecodeBBensemble( void )
{
unsigned short i, *IDptr, ID;
FLdrPtr = (FixLeaderType *)&RcvBuff [ HdrPtr->Offset[0] ];
if (FLdrPtr->NBins > 128)
FLdrPtr->NBins = 32;

...

The bit I am having difficulty following is this:

FLdrPtr = (FixLeaderType *)&RcvBuff [ HdrPtr->Offset[0] ];

From the little I understand, [ HdrPtr->Offset[0] ]; would be returning the value of the first Offset array item from the HeaderType struct pointed to by HdrPtr? So equivalent to HdrPtr^.Offset[0] ?

Then &RcvBuff [ HdrPtr->Offset[0] ]; should be returning the memory address containing the value of the RcvBuff array item indexed, so equivalent to @RecBuff[HdrPtr^.Offset[0]] ?

Then I get lost with (FixLeaderType *).. . Could someone please help explain exactly what is being referenced by FldrPtr ?

2 Answers 2

4

The bits of code that are relevant are

FixLeaderType *FLdrPtr; 
unsigned char RcvBuff[8192]; 

FLdrPtr = (FixLeaderType *)&RcvBuff [ HdrPtr->Offset[0] ]; 
  1. FldPtr is of type FixLeaderType *, or pointer to FixLeaderType.
  2. RcvBuff is an array of char.
  3. HdrPtr->Offset[0] resolves to an ushort value, so RcvBuff [ HdrPtr->Offset[0] ] yields a char value.
  4. The & means that instead of getting the value of the char the address of the value is returned. Note that this means that it is of type char *.
  5. The char * type is the wrong type to assign to FldPtr. The (FixLeaderType *) converts the type so that it is valid. This is called a cast operation.
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! The typecast operation was the bit I was missing. That clears things up enough for me to continue. Cheers.
"RcvBuff is an array of char" - Correct in Delphi 2007 and older. But in Delphi 2009 and newer it should instead be: "RcvBuff is an array of AnsiChar". Or alternatively: "RcvBuff is an array of Byte". This change is due to the fact that in Delphi 2007 and older: char = alias that means AnsiChar. But in Delphi 2009 and newer: char = alias that means WideChar.
3

i think you should read those like:

* = pointer to

& = address of

that makes things a lot easier

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.