Swift, Strings and Memory Addresses

不想你离开。 提交于 2019-11-26 22:59:10
Martin R
func unsafeAddressOf(object: AnyObject) -> UnsafePointer<Void>

takes an AnyObject parameter, i.e. an instance of a class. It returns the pointer to the storage used for the object referenced by object.

addressOf() cannot be used with struct variables:

struct Foo { }
var f = Foo()
let a = unsafeAddressOf(f)
// error: cannot invoke 'unsafeAddressOf' with an argument list of type '(Foo)'

String is a struct, however, it is automatically bridged to NSString when passed to a function expecting an object. So

let word0 = "hello"
let p1 = unsafeAddressOf(word0)

actually executes

let p1 = unsafeAddressOf(word0 as NSString)

You get not the address of the word0 variable, but the pointer to the memory location of the bridged NSString object.

It seems that you cannot make any assumptions on whether this bridging returns the identical NSString object (or more generally, the same Foundation object) when done repeatedly on the same Swift string. In a Playground, even

let word0 = "hello"
let p1 = unsafeAddressOf(word0)
let p2 = unsafeAddressOf(word0)
let p3 = unsafeAddressOf(word0)

returns three different addresses (but the same addresses in a compiled project). The same observation (for arrays and dictionaries) was made in A different bridging between Array and Dictionary.

Swift 3.0 Unmanaged.passUnretained(object).toOpaque()

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!