comar comar - 2 months ago 11
Objective-C Question

Type conversation of byte array between Objective-C and Swift

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_LENGTH
is 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

Answer

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.)