简体   繁体   English

如何快速声明#pragma pack(1)

[英]How to declare #pragma pack (1) in swift

I'm trying to rewrite an iOS app from objective c into swift. 我正在尝试将iOS C从目标C重写为Swift。 I'm using serialization in order to send data over some sort of communication layer. 我正在使用序列化以便通过某种通信层发送数据。 In objective c I used #pragma pack (1) at the top of each struct in order to use sequential layout without padding between the data members. 在目标c中,我在每个结构的顶部使用#pragma pack(1),以便使用顺序布局而不在数据成员之间填充。 I tried to use PRAGMA_STRUCT_PACK at the top of the struct. 我试图在结构顶部使用PRAGMA_STRUCT_PACK。 It seems to work at the playground, but when implementing it in my app, I got an error message saying: "Expressions are not allowed at the top level". 它似乎可以在操场上工作,但是在我的应用程序中实现它时,我收到一条错误消息:“不允许在顶层进行表达式”。

从游乐场在此处输入图片说明

Swift doesn't support explicitly specifying the data layout of structure types. Swift不支持显式指定结构类型的数据布局。 (At least, not currently. File a bug if there are features you'd like to see and maybe Apple will put them in a future version?) For now your best bet is probably to declare layout-sensitive structures (and functions to access them) in C and call those from Swift. (至少目前没有。 文件中的错误 ,如果有功能,你想看到的,也许苹果将让他们在未来的版本?)现在你最好的选择可能是申报布局敏感的结构(和功能访问他们)在C中,然后从Swift调用它们。

Writing PRAGMA_STRUCT_PACK in Swift source gives you an error because that macro, once imported from C, evaluates to the literal 1 . 在Swift源代码中编写PRAGMA_STRUCT_PACK会给您带来错误,因为从C导入后,该宏的结果为文字1 In C, you're supposed to use that macro to detect whether the compiler supports #pragma pack (before going on to issue a #pragma pack directive). 在C语言中,应该使用该宏来检测编译器是否支持#pragma pack (在继续发出#pragma pack指令之前)。

(You're probably seeing confusing answers/comments because lots of people were looking for #pragma mark during the early Swift betas. But this isn't the #pragma they're talking about.) (您可能会看到令人困惑的答案/评论,因为许多人在早期的Swift测试版中都在寻找#pragma mark 。但这不是他们在谈论的#pragma 。)

Swift is not C. If you care about layout of structures in memory, you are in the wrong place. Swift不是C。如果您关心内存中结构的布局,那么您来错了地方。 I mean why on earth would you be interested in that kind of implementation detail? 我的意思是,为什么您会对这种实施细节感兴趣? Swift will layout things the way it wants and no other way. Swift会按照自己想要的方式布局事物,而没有其他方式。 It's not an assembly language. 它不是汇编语言。

BTW. 顺便说一句。 Trying to use packed structures for serialization is totally misguided. 尝试使用打包结构进行序列化是完全错误的。 Create an array of bytes and write to it what you want to write. 创建一个字节数组,然后将要写入的内容写入其中。

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

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