简体   繁体   中英

How can I use an array of bytes to initialize a struct object in Swift?

First, I am coming from a C programming background. My system consists of a device that is using software written in C language which utilizes Bluetooth to talk to the iPhone Application. I have a struct defined on the C device that I send byte by byte through Bluetooth and I am trying to reconstruct the struct in Swift.

In C, I would use a pointer to the array of bytes and simply typecast it to a pointer of my custom struct type:

uint8_t arrayOfBytes[16];

CustomStructType_t * structPtr = (CustomStructType_t *)arrayOfBytes;

In C, this is simple. I had an array of bytes, but I used typecasting to represent it as a custom struct instead.

Now on the iPhone, I capture the incoming Bluetooth bytes using Core Bluetooth. When a characteristic is updated, the following line accepts the bluetooth packet and converts it from Data type to String of bytes.

let incomingByteString = String(data: receivedBluetoothDataPacket, encoding: String.Encoding.utf8)

I'm honestly super lost at this point. I want to use this packet to initialize, or update the values of a struct object, lets say:

struct CustomStruct {
  let name: String!
  let value: Int
}

It would be nice if I could just tell Swift, Hey, I want you to create a CustomStruct object out of this incomingByteString.

Looks like this is going to be a real pain, and I may need to format the incoming packet much differently to accommodate Swift. Any advice is appreciated.

Try this

let bytes: [UInt8] = //get your bytes here
let customStruct = bytes.withUnsafeBufferPointer {
    ($0.baseAddress!.withMemoryRebound(to: CustomStruct.self, capacity: 1) { $0 })
}.pointee

You would have to convert your receivedBluetoothDataPacket to [UInt8] and you haven't provided the exact type.

Assuming it's Data a simple [UInt8](receivedBluetoothDataPacket) should suffice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM