1

Given

public struct MIDIPacketList {
    public var numPackets: UInt32
    public var packet: (MIDIPacket)
}

I would like to access an UnsafeMutablePointer of packet, given I have an UnsafeMutablePointer. Merely getting a copy of the original packet member is easy, but not correct: I need the pointer itself. In C, what I would like to achieve is as simple as

MIDIPacket *packet = &packetList->packet;

How do I do the same in Swift? Note that while I think advancing by 4 bytes (size of UInt32) does most likely work as a hack, but it is an incorrect answer because of structure alignment issues.

Zsolt Szatmari
  • 1,219
  • 1
  • 12
  • 29

1 Answers1

2

This should work:

let packetList: UnsafeMutablePointer<MIDIPacketList> = ...

withUnsafeMutablePointer(to: &packetList.pointee.packet) {
    packet in // UnsafeMutablePointer<(MIDIPacket)>
    // ...
}

Inside the closure, packet is a pointer to the MIDIPacket.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382