简体   繁体   English

Objective-C和C ++中结构的大小

[英]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. 我正在将一些Objective-C ++代码转换为普通的Objective-C,我遇到了一些结构问题。 For both languages, I have the struct declared in the .h file like this. 对于这两种语言,我在.h文件中声明了这样的结构。

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

In C++, the struct is being declared like 在C ++中,结构被声明为

BasicNIDSHeader header;

and in Objective-C I do this 在Objective-C中,我这样做

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. 其中fileHandle是NSFileHandle。

The problem is than in the original C++ code, sizeof(header) = 18. When using Objective-C, sizeof(header) = 20. 问题是在原始C ++代码中,sizeof(header)= 18.使用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++. 代码依赖于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. 如果你依赖于struct的内部内存结构 - 你应该禁用填充。 This is called "packed", and different compilers have different ways of signalling it. 这称为“打包”,不同的编译器有不同的信号发送方式。

In GCC you do this with the __attribute__ keyword. 在GCC中,您可以使用__attribute__关键字执行此操作。 Details here . 细节在这里

I can only speak for C++. 我只能说C ++。 In C++ there is an implementation specific feature which aligns the data on specific addresses, so that data can be processed efficently. 在C ++中,有一个特定于实现的特性,它使特定地址上的数据对齐,从而可以有效地处理数据。

In MS Visual C++ you can enforce byte alignment with a pragma: 在MS Visual C ++中,您可以使用pragma强制执行字节对齐:

#pragma pack(1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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