Skip to content

Instantly share code, notes, and snippets.

@donly
Last active November 18, 2016 08:08
Show Gist options
  • Save donly/91529f49756c0de2a10cf4d972e59df1 to your computer and use it in GitHub Desktop.
Save donly/91529f49756c0de2a10cf4d972e59df1 to your computer and use it in GitHub Desktop.
Using pointer in Swift 3
//: Playground - noun: a place where people can play
import Foundation
var str = "Hello"
let data1 = str.data(using: String.Encoding.utf8)!
data1.withUnsafeBytes { (bytes: UnsafePointer<CChar>) -> Void in
print(bytes.pointee)
let arr = UnsafeBufferPointer(start: bytes, count: 5)
arr.forEach({
print($0)
})
}
/*
let a = UnsafeMutablePointer<Int>.allocate(capacity: 1)
a.pointee = 4
print("a = \(a.pointee)")
a.deallocate(capacity: 1)
*/
/*
// & operator with UnsafePointer
func receive(pointer: UnsafePointer<Int>) {
print("param value is: \(pointer.pointee)")
}
var a = 42
receive(pointer: &a)
*/
/*
// & operator with UnsafeMutablePointer
func receive(mutablePointer: UnsafeMutablePointer<Int>) {
mutablePointer.pointee *= 2
}
var a = 10
receive(mutablePointer: &a)
print("a = \(a)")
*/
//var a = 1024
//withUnsafeMutablePointer(to: &a) {
// $0.pointee *= 2
//}
// 指针转换
var addrIn = sockaddr_in()
// Fill sockaddr_in fields
withUnsafePointer(to: &addrIn) { ptr in
ptr.withMemoryRebound(to: sockaddr.self, capacity: 1, { ptrSockAddr in
bind(1, UnsafePointer(ptrSockAddr), socklen_t(MemoryLayout<sockaddr>.size))
})
}
let intPtr = UnsafeMutablePointer<Int>.allocate(capacity: 1)
let voidPtr = UnsafeRawPointer(intPtr)
let intPtrAgain = voidPtr.assumingMemoryBound(to: Int.self)
// 数组指针
let size = 10
var a = UnsafeMutablePointer<Int>.allocate(capacity: size)
for idx in 0..<10 {
a.advanced(by: idx).pointee = idx*2
}
a.advanced(by: 1).pointee
a.advanced(by: 9).pointee
// UnsafeBufferPointer 这个结构体是一个Swift数组和指针的桥梁
var b = UnsafeBufferPointer(start: a, count: size)
b.forEach {
print("\($0)")
}
var c = [1, 2, 3, 4, 5, 6]
c.withUnsafeBufferPointer({ ptr in
ptr.forEach({ print("\($0)") }) // 1, 2, 3...
})
// 内存管理带来的危害
// 然而我们我们是使用 unsafe 引用来混合两个世界(不需要内存管理和手动内存管理)
var collectionPtr: UnsafeMutableBufferPointer<Int>?
func duplicateElements(inArray: UnsafeMutableBufferPointer<Int>) {
for i in 0..<inArray.count {
inArray[i] *= 2
}
}
repeat {
var collection = [1, 2, 3]
collection.withUnsafeMutableBufferPointer({
collectionPtr = $0
})
collectionPtr?.forEach({
print($0) // 正常
})
} while false
collectionPtr?.forEach({
print($0) // error
})
duplicateElements(inArray: collectionPtr!)
a.deallocate(capacity: size)
// 使用 bitPattern 来修改指针的值
//pass
// 透明指针
// no data here
// see more here, http://technology.meronapps.com/2016/09/27/Swift-3-0-unsafe-world-2/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment