简体   繁体   中英

How to declare #pragma pack (1) in swift

I'm trying to rewrite an iOS app from objective c into 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. I tried to use PRAGMA_STRUCT_PACK at the top of the struct. 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. (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.

Writing PRAGMA_STRUCT_PACK in Swift source gives you an error because that macro, once imported from C, evaluates to the literal 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).

(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 is not C. If you care about layout of structures in memory, you are in the wrong place. 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. 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.

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