2

I am using a library written in Objective-C which has a property that is organised as a struct and includes a byte array:

typedef struct {
    byte                ID[MAX_ID_LENGTH];
    short               Length;
    ...
} RFIDTag;

MAX_ID_LENGTHis a constant with the value 64.

I bridged the library to my swift project, which works fine so far but I am wondering about the return type of the Property RFIDTag.ID which is

byteID (UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8) in swift. Every byte value can be accessed via the property RFIDTag.ID.0, RFIDTag.ID.1 and so on

But I want to store the whole ID in an array without manually copying every single value.

At this, I am not able to assign the ID property to a swift array that was initialised according to var array = [UInt8](count:64, repeatedValue:0) or similar.

Does anybody has an idea how to solve this issue?

Thanks in advance and regards

Marco

Janmenjaya
  • 4,149
  • 1
  • 23
  • 43
comar
  • 43
  • 6

1 Answers1

2

You can copy these values into an Array by constructing it from a buffer pointer. For example:

let array: [UInt8] = withUnsafePointer(&byteID) { bytePtr in
    let buffer = UnsafeBufferPointer(start: UnsafePointer<UInt8>(bytePtr), count: 64)
    return Array(buffer)
}

This creates a pointer to the tuple, converts it to a pointer to an UInt8, converts that to a buffer, and then uses the buffer to initialize the Array. Note that byteID must be a var, not a let value, so that you can use & on it. This may force you to make two copies of the tuple. (I'm pretty sure there's another technique that could avoid that extra copy, but it probably isn't a big deal in this case.)

Rob Napier
  • 286,113
  • 34
  • 456
  • 610