0

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?

2
  • 1
    Possibly helpful: stackoverflow.com/q/27455773/1187415. Commented Jul 19, 2019 at 21:19
  • @MartinR you mean something like this: memcpy(&myId, withUnsafePointer(to: packet?.header().pointee.m1){$0}, 6) ? Commented Jul 19, 2019 at 21:28

1 Answer 1

3

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))
}
Sign up to request clarification or add additional context in comments.

2 Comments

I think it works (yay!, thanks for that), but wouldn't memcpy work too?
That would be withUnsafePointer(to: headerStruct.pointee.m1) { memcpy(&myId, $0, 6) }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.