Swift, Strings and Memory Addresses

后端 未结 2 1417
谎友^
谎友^ 2020-11-28 14:50

There is something I am not understanding about how Swift manages memory address of String(s)

1. Reference types

Here foo and

相关标签:
2条回答
  • 2020-11-28 15:00
    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.

    0 讨论(0)
  • 2020-11-28 15:16

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

    0 讨论(0)
提交回复
热议问题