How can I get a memory address like value or custom structure in Swift?

I am trying to get a deeper understanding of how Swift copies value types :

The behavior you see in your code will always be as if the copy took place. However, Swift only performs the actual copy backstage when absolutely necessary.

To advance my understanding, I would like to get a memory address of type value. I tried unsafeAddressOf (), but this does not work with structures and it seems to use the Swift standard library types for reference types (e.g. String is passed to NSString).

How to get a memory address of a value type, for example an Int instance, or a custom structure in Swift?

+7
struct ios swift swift2
source share
3 answers

According to the answer of Martin R.

addressOf () cannot be used with structured variables. String is a structure, however, it automatically connects to NSString when passing a function that expects an object.

According to nschum's answer, you can get the (stack) address of a struct , such as a built-in type or object, for example:

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" 

I found that if myStruct does not matter, the address will be kept the same:

 struct myStruct { } var struct1 = myStruct() var struct2 = struct1 print(NSString(format: "%p", address(&struct1))) // -> ""0xa000000000070252\n"" print(NSString(format: "%p", address(&struct2))) // -> ""0xa000000000070252\n"" 
+13
source share

Swift 2.0:

You can use this unsafeAddressOf(someObject)

or in Swift 3.0:

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

+6
source share

I'm not sure if there is a “recommended” way to do this, but one method is to use withUnsafePointer(_:_:) , for example:

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

Printed 0x00007ffff52a011c8 on my machine.

+4
source share

All Articles