Search code examples
swiftunsafe-pointers

How do I access UnsafePointer of member field of a struct referenced by an UnsafePointer in Swift?


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.


Solution

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