[swift-evolution] Proposal: Add Initializers For Converting UnsafePointers to Int and Unit

Brent Royal-Gordon brent at architechies.com
Wed Dec 9 15:15:04 CST 2015


> On the off chance you're trying to do loads from unaligned UnsafePointers, that's undefined in the current interface. You'll need to memcpy to well-aligned memory first.

The buffer I’m accessing is UInt8, which I believe is always aligned, right?

C:

	typedef struct MIDIMetaEvent
	{
		UInt8		metaEventType;
		UInt8		unused1;
		UInt8		unused2;
		UInt8		unused3;
		UInt32		dataLength;
		UInt8		data[1];
	} MIDIMetaEvent;

Swift:

	public struct MIDIMetaEvent {
	    
	    public var metaEventType: UInt8
	    public var unused1: UInt8
	    public var unused2: UInt8
	    public var unused3: UInt8
	    public var dataLength: UInt32
	    public var data: (UInt8)
	    public init()
	    public init(metaEventType: UInt8, unused1: UInt8, unused2: UInt8, unused3: UInt8, dataLength: UInt32, data: (UInt8))
	}

For obvious reasons, Swift doesn’t understand the actual size of this data structure and only copies the amount of data it knows about. (It also has to be allocated with malloc(), because UnsafePointer.alloc() takes a number of objects, not a number of bytes. He was apparently in contact with someone at Apple about this MIDI stuff, and the “the guy on my team who knows Swift” *didn’t* know this.) We had to always access it through an UnsafePointer, and construct an UnsafeBufferPointer from &data and dataLength. That all actually worked pretty straightforwardly, but then I started playing with the idea of a general purpose type to manage this kind of pointer, and it was at that point that I started doing ugly pointer arithmetic (to try to access the variable-length buffer at he end of the type).

-- 
Brent Royal-Gordon
Architechies



More information about the swift-evolution mailing list