[swift-evolution] Proposal: Add Initializers For Converting UnsafePointers to Int and Unit
Joe Groff
jgroff at apple.com
Wed Dec 9 14:59:13 CST 2015
> On Dec 9, 2015, at 12:56 PM, Brent Royal-Gordon via swift-evolution <swift-evolution at swift.org> wrote:
>
>> extension UInt {
>> init<T>(bitPattern: UnsafePointer<T>) {
>> self = UInt(Builtin.ptrtoint_Word(bitPattern._rawValue))
>> }
>>
>> init<T>(bitPattern: UnsafeMutablePointer<T>) {
>> self = UInt(Builtin.ptrtoint_Word(bitPattern._rawValue))
>> }
>> }
>
> I was helping someone in my NSCoder Night group struggle with UnsafePointer just last night. He was working with MIDIMetaEvent, a C struct with a variable-sized buffer at the end of it. There was just no good way to handle the allocation and use of this type; I ended up writing an extension full of bizarre magic just so he could access and use it..
>
> Anyway, all this is to say I would have used these initializers if they’d existed, and the alignment stuff you’re suggesting probably wouldn’t have cut the mustard for some of what I was trying to do.
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.
-Joe
More information about the swift-evolution
mailing list