C struct handling for Swift
Class for packing and unpacking C structs in Swift, modeled after the struct module in Python.
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
}
}
func unpack(data: NSData, format: String, error: NSErrorPointer) -> AnyObject[]?
func unpack(data: NSData, error: NSErrorPointer) -> AnyObject[]?
func pack(values: AnyObject[], format: String, error: NSErrorPointer) -> NSData?
func pack(values: AnyObject[], error: NSErrorPointer) -> NSData? {
BYTE ORDER
SIZE
ALIGNMENT
@
native
native
native
=
native
standard
none
<
little-endian
standard
none
>
big-endian
standard
none
!
network (BE)
standard
none
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