# Pointer と向き合う / Facing the Pointer

（https://bitkey.connpass.com/event/317143/

May 15, 2024

## Transcript

Expands! #2 Masatoshi Tsushima

Tsushima 2004 ιϑτ΢ΣΞ։ൃͱͷग़ձ͍ WebαΠτ΍ܞଳΞϓϦΛ࡞ͬͯ༡ΜͰ͍·ͨ͠ 2018ळ Bitkeyʹࢀը ౰ॳ͸bitkey platformͷ։ൃΛ୲౰ ओʹGoͰαʔόαΠυΛ։ൃ 2019ळ ϑΝʔϜ΢ΣΞνʔϜΛ্ཱͪ͛ bitlock LITEͷϑΝʔϜ΢ΣΞΛ಺੡Խ ݱࡏʹଓ͘։ൃελΠϧΛߏங 2020Ն ୈೋੈ୅ϩοΫσόΠεͷ։ൃ ಺੡Λલఏͱͨ͠ϑΝʔϜ΢ΣΞ։ൃ 2021य़ϦϦʔε 2022Ն Individual contributor (?) Android/iOS/FlutterɺσόΠεQA༻ΞϓϦɺࣾ಺ ࢓༷ͷඪ४ԽɺMakefile৬ਓɺCI͓͡͞Μ

iOS ։ൃʹҟಈ͢Δ·Ͱ͸ var x = 1 let p = UnsafePointer(&x) print("\(p.pointee), \(p)")

ओʹόΠτྻͷૢ࡞ • C ݴޠͷ഑ྻ • Swift ͷ Array/Data ಡΈସ͑ɾॻ͖׵͑ɾసૹɾಠࣗͷ؅ཧ…

ʹ͍ͨ͠ ݕࡧ͢ΔͱΑ͘ग़ͯ͘Δ΍ͭ import Foundation let data = Data([1, 2, 3, 4]) let x = data.withUnsafeBytes { \$0.load(as: UInt16.self) } print(x) // Output: 513

ʹ͍ͨ͠ load ͷ୅ΘΓʹ OpaquePointer Λܦ༝ͤͯ͞Έͨ import Foundation let data = Data([1, 2, 3, 4]) let x = data.withUnsafeBytes { UnsafePointer<UInt16>(OpaquePointer(\$0.baseAddress!)).pointee } print(x) // Output: 513 खݩͰ͸ -O -emit-assembly Ͱಉ݁͡Ռ

λʔήοτͱҟͳΔͳΒٯॱʹ͢Δ print(x) // Apple Silicon ͸ 513 print(x.bigEndian) // 258 print(x.littleEndian) // 513 print(x.bigEndian.bigEndian) // 513 print(x.littleEndian.littleEndian) // 513

Alignment Λௐ੔͢Δखஈʹ͚ܽΔ

• UnsafeMutablePointer<T> • UnsafeRawPointer • UnsafeMutableRawPointer • UnsafeBufferPointer<T> • UnsafeMutableBufferPointer<T> • UnsafeRawBufferPointer • UnsafeMutableRawBufferPointer Mutable ॻ͖׵͑Մೳ Buffer ௕͞ (count) ෇͖ Raw ૯শܕ (<T>) ແ͠

UnsafePointer<T> • UnsafeMutablePointer<T> • UnsafeRawPointer • UnsafeMutableRawPointer • UnsafeBufferPointer<T> • UnsafeMutableBufferPointer<T> • UnsafeRawBufferPointer • UnsafeMutableRawBufferPointer

• ະ֬อ ◦ ࢦࣔ͢͠ઌ͕֬อ͞Ε͍ͯͳ͍͔΋ • ະॳظԽ ◦ ॳظԽ͞Ε͍ͯͳ͍͔΋ • ະ։์ ◦ ։์͞Εͳ͍͔΋

x: Int = 10 let p = UnsafePointer<Int>(&x) print(p.advanced(by: 10).pointee)

x: Int = 10 let p = UnsafePointer<Int>(&x) print(p.advanced(by: 10).pointee) ਖ਼ৗऴྃͪ͠Ό͏Μͩͳ͜Ε͕…

Foundation let data = Data([1, 2, 3, 4]) let x = data.withUnsafeBytes { let op = OpaquePointer(\$0.baseAddress!.advanced(by: 10)) return UnsafePointer<UInt16>(op).pointee } print(x) load ͷ count νΣοΫΛආ͚Δͱਖ਼ৗऴྃ͢Δ

for _ in 1...1_000_000 { let _ = UnsafeMutablePointer<Int> .allocate(capacity: 1_000) }

֬อͨ͠͸ͣͰ͸…ʁ