如何在Swift中获取值类型或自定义结构的内存地址?

时间:2016-05-23 23:09:29

标签: ios swift struct swift2 swift2.2

我正在努力深入了解Swift copies value types

  

您在代码中看到的行为将始终如同副本一样   地点。但是,Swift仅在幕后执行实际复制   当绝对有必要的时候。

为了提高我的理解,我想得到一个值类型的内存地址。我尝试了unsafeAddressOf(),但this doesn't work with structs and it seems to cast Swift's standard library types to reference types(例如String被强制转换为NSString)。

如何获取值类型的内存地址,如Int实例或Swift中的自定义结构?

3 个答案:

答案 0 :(得分:19)

根据Martin R'回答

  

addressOf()不能与struct变量一起使用。 String是一个结构,但是,当传递给期望对象的函数时,它会自动桥接到NSString。

根据nschum的回答,您可以获得 struct (内置类型)或对象引用的(堆栈)地址,如下所示:

import UIKit


func address(o: UnsafePointer<Void>) -> Int {
    return unsafeBitCast(o, Int.self)
}

func addressHeap<T: AnyObject>(o: T) -> Int {
    return unsafeBitCast(o, Int.self)
}


struct myStruct {
    var a: Int
}

class myClas {

}
//struct
var struct1 = myStruct(a: 5)
var struct2 = struct1
print(NSString(format: "%p", address(&struct1))) // -> "0x10f1fd430\n"
print(NSString(format: "%p", address(&struct2))) // -> "0x10f1fd438\n"

//String
var s = "A String"
var aa = s
print(NSString(format: "%p", address(&s))) // -> "0x10f43a430\n"
print(NSString(format: "%p", address(&aa))) // -> "0x10f43a448\n"

//Class
var class1 = myClas()
var class2 = class1
print(NSString(format: "%p", addressHeap(class1))) // -> 0x7fd5c8700970
print(NSString(format: "%p", addressHeap(class2))) // -> 0x7fd5c8700970

unsafeAddressOf(class1) //"UnsafePointer(0x7FD95AE272E0)"
unsafeAddressOf(class2) //"UnsafePointer(0x7FD95AE272E0)"

//Int
var num1 = 55
var num2 = num1
print(NSString(format: "%p", address(&num1))) // -> "0x10f1fd480\n"
print(NSString(format: "%p", address(&num2))) // -> "0x10f1fd488\n"

我发现的一件事是,如果myStruct没有值,地址将保持不变:

struct myStruct {

}

var struct1 = myStruct()
var struct2 = struct1
print(NSString(format: "%p", address(&struct1))) // -> ""0xa000000000070252\n""
print(NSString(format: "%p", address(&struct2))) // -> ""0xa000000000070252\n""

答案 1 :(得分:9)

Swift 2.0:

您可以使用此unsafeAddressOf(someObject)

或在Swift 3.0中:

使用withUnsafePointer(to: someObejct) { print("\($0)") }

答案 2 :(得分:5)

我不确定是否有&#34;推荐&#34;这样做的方法,但一种方法是使用withUnsafePointer(_:_:),如下所示:

var s: String = "foo"
withUnsafePointer(&s) { NSLog("\($0)") }

我的机器上打印了0x00007ffff52a011c8