3

I am converting some Objective-C++ code into plain Objective-C and I am having some trouble with structs. For both languages, I have the struct declared in the .h file like this.

struct BasicNIDSHeader {
    short messageCode;
    short messageDate;
    int messageTime;
    int messageLength;
    short sourceID;
    short destID;
    short numberOfBlocks;
};

In C++, the struct is being declared like

BasicNIDSHeader header;

and in Objective-C I do this

struct BasicNIDSHeader header;

The code for using them is actually the same in both languages.

memset(&header, 0, sizeof(header));
[[fileHandle readDataOfLength:sizeof(header)] getBytes:&header];

where fileHandle is a NSFileHandle.

The problem is than in the original C++ code, sizeof(header) = 18. When using Objective-C, sizeof(header) = 20.

Any ideas why this is happening or how to fix it? The code is dependent on the size being like it is in C++. I can just hardcode it, but would like to have a better understanding of why it is happening. Plus I hate hardcoding constants.

Thanks!

Ross Kimes
  • 1,234
  • 1
  • 12
  • 34
  • You could use a typedef and then you don't need to modify all your declarations. – sidyll Jan 03 '12 at 22:06
  • 1
    You could see the place where there's change by printing `&header`, `&header.messageCode`, `&header.messageDate`, etc. in both languages, and see if there is a gap, or there's padding at the end. – Sergey Kalinichenko Jan 03 '12 at 22:08
  • 2
    Are you using C++ at all, or just Objective-C++ (in addition to Objective-C)? The code you showed, which is "the same in both languages", certainly isn't C++. – Keith Thompson Jan 03 '12 at 22:24

2 Answers2

2

If you depend on the internal memory structure of your structs - you should disable padding. This is called "packed", and different compilers have different ways of signalling it.

In GCC you do this with the __attribute__ keyword. Details here.

littleadv
  • 20,100
  • 2
  • 36
  • 50
0

I can only speak for C++. In C++ there is an implementation specific feature which aligns the data on specific addresses, so that data can be processed efficently.

In MS Visual C++ you can enforce byte alignment with a pragma:

#pragma pack(1)
frast
  • 2,700
  • 1
  • 25
  • 34