John Smith
John Smith

Reputation: 591

Swift | Get pointer of c char array inside struct

I'm trying to convert some old ObjC code to Swift, I haven't done a lot with Swift regarding Pointers.

Original ObjC/C code:

unsigned char myId[6];
memcpy(myId, packet.header->m1, 6);

Original C Struct:

typedef struct {
    unsigned char m1[6];
    unsigned char m2[6];
} __attribute__((__packed__)) HeaderStruct;

My tried Swift code, not working:

var myId = [CUnsignedChar](repeating: 0, count: 6)
var headerStruct: UnsafePointer<HeaderStruct> = packet!.header()
memcpy(&myId, headerStruct.pointee.m1, 6)

The error regarding headerStruct.pointee.m1

Cannot convert value of type '(UInt8, UInt8, UInt8, UInt8, UInt8, UInt8)' to expected argument type 'UnsafeRawPointer?'

I assume I need the base address (headerStruct) and add the offset for the m1, but how do I do that?

Upvotes: 0

Views: 408

Answers (1)

Martin R
Martin R

Reputation: 539715

A C array is imported to Swift as a tuple. But the memory layout is preserved, therefore you can obtain a pointer to the storage of the tuple and “bind” it to a pointer to UInt8 values:

let myId = withUnsafeBytes(of: headerStruct.pointee.m1) {
    Array($0.bindMemory(to: UInt8.self))
}

Upvotes: 3

Related Questions