Skip to content

Class for packing and unpacking C structs in Swift

Notifications You must be signed in to change notification settings

csann/MVPCStruct

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

15 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

C struct handling for Swift

Class for packing and unpacking C structs in Swift, modeled after the struct module in Python.

Sample Code

import MVPCStruct

// Receiver expects a message with a header like this:
//  typedef struct {
//      uint16_t version;  // Message format version, currently 0x0100.
//      uint16_t reserved; // Reserved for future use.
//      uint32_t length;   // Length of data in bytes.
//      uint8_t data[];    // Binary encoded plist.
//  } __attribute__((packed)) mma_msg_t;
func sendMessageHeader(msgData: NSData) -> Bool {
    var error: NSError?
    
    let version = 0x0100
    let reserved = 0
    
    let packer = CStruct(format: "=HHI")
    if let packedHeader = packer.pack([version, reserved, msgData.length], error: &error) {
        return 8 == send(socket_fd, packedHeader.bytes, packedHeader.length)
    } else {
        return false
    }
}

Tasks

Creating CStruct Objects

- initWithFormat:

init(format: String)

Unpacking data

- unpack:format:error:

func unpack(data: NSData, format: String, error: NSErrorPointer) -> AnyObject[]?

- unpack:error:

func unpack(data: NSData, error: NSErrorPointer) -> AnyObject[]?

Packing values

- pack:format:error:

func pack(values: AnyObject[], format: String, error: NSErrorPointer) -> NSData?

- pack:error:

func pack(values: AnyObject[], error: NSErrorPointer) -> NSData? {

Format strings

Control characters

BYTE ORDER SIZE ALIGNMENT
@ native native native
= native standard none
< little-endian standard none
> big-endian standard none
! network (BE) standard none

Format characters

FORMAT C TYPE SWIFT TYPE SIZE
x pad byte no value
c char String of length 1 1
b signed char Int 1
B unsigned char UInt 1
? _Bool Bool 1
h short Int 2
H unsigned short UInt 2
i int Int 4
I unsigned int UInt 4
l long Int 4
L unsigned long UInt 4
q long long Int 8
Q unsigned long long UInt 8
f float Float 4
d double Double 8
s char[] String
p char[] String
P void * UInt 4/8

About

Class for packing and unpacking C structs in Swift

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • Swift 98.2%
  • C++ 1.8%