[swift-users] raw buffer pointer load alignment

Johannes Weiß johannesweiss at apple.com
Wed Nov 8 19:04:58 CST 2017


Hi Kelvin,

> On 8 Nov 2017, at 4:54 pm, Kelvin Ma via swift-users <swift-users at swift.org> wrote:
> 
> According to the docs, the load(fromByteOffset:as:) method requires the instance to be “properly aligned” Does that mean if I have raw data meant to be interpreted as 
> 
> 0      1      2      3      4      5      6
> [ Int8 |    Int16    |    Int16    | Int8 | Int8 ]
> 
> 
> i can’t just load the Int16 from byte offset 1?

you can't just dereference that pointer as an Int16 (in any language) without causing UB but it's not really an issue, just do this (assuming `ptr` is the pointer into your data and `index` is the index to where your Int16 lives):


    var value: Int16 = 0
    withUnsafeMutableBytes(of: &value) { valuePtr in
        valuePtr.copyBytes(from: UnsafeRawBufferPointer(start: ptr.baseAddress!.advanced(by: index),
                                                        count: MemoryLayout<Int16>.size))
    }

you can have the whole thing generic too for <T: FixedWidthInteger>

    var value: T = 0
    withUnsafeMutableBytes(of: &value) { valuePtr in
        valuePtr.copyBytes(from: UnsafeRawBufferPointer(start: ptr.baseAddress!.advanced(by: index),
                                                        count: MemoryLayout<T>.size))
    }

-- Johannes


> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users



More information about the swift-users mailing list