简体   繁体   中英

Size of Structs in Objective-C and C++

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!

If you depend on the internal memory structure of your struct s - 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 .

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM