-
-
Save sunilsharma08/3e19bd24e16f9713ab8d6c1778a1eed7 to your computer and use it in GitHub Desktop.
Get the memory address of both class and structure instances in Swift.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // https://stackoverflow.com/a/45777692/5536516 | |
| import Foundation | |
| /* For objects */ | |
| class MyClass { var foo = 1 } | |
| var myClass = MyClass() | |
| let opaquePointer = Unmanaged<AnyObject>.passUnretained(myClass).toOpaque() | |
| print(opaquePointer) | |
| let intPointer = unsafeBitCast(myClass, to: Int.self) | |
| print(String(format: "%p", intPointer)) | |
| /* For structures */ | |
| struct MyStruct { var foo = 1 } | |
| var myStruct = MyStruct() | |
| let unsafeMutablePointer = UnsafeMutablePointer<MyStruct>(&myStruct) | |
| print(unsafeMutablePointer) | |
| let pointerWithUnmanaged = Unmanaged<AnyObject>.fromOpaque(&myStruct).toOpaque() | |
| print(pointerWithUnmanaged) | |
| let pointerFromClosure = { (p: UnsafePointer) in p }(&myStruct) | |
| print(pointerFromClosure) | |
| withUnsafePointer(to: &myStruct) { print($0) } | |
| func getStructAddress(p: UnsafeRawPointer) { | |
| // Warning: 'unsafeBitCast' from 'UnsafeRawPointer' to 'Int' | |
| // can be replaced with 'bitPattern:' initializer on 'Int' | |
| let pointerFromBitCast = unsafeBitCast(p, to: Int.self) | |
| print(String(format: "%p", pointerFromBitCast)) | |
| let pointerFromInt = Int(bitPattern: p) | |
| print(String(format: "%p", pointerFromInt)) | |
| } | |
| getStructAddress(p: &myStruct) | |
| /* output | |
| 0x0000000100f063d0 | |
| 0x100f063d0 | |
| 0x000000010040f498 | |
| 0x000000010040f498 | |
| 0x000000010040f498 | |
| 0x000000010040f498 | |
| 0x10040f498 | |
| 0x10040f498 | |
| /* | |
| /* verifying | |
| (lldb) frame variable -L myClass | |
| scalar(0x0000000100f063d0): (GetAnyAddress.MyClass) myClass = 0x0000000100f063d0 { | |
| 0x0000000100f063e0: foo = 1 | |
| } | |
| (lldb) frame variable -L myStruct | |
| 0x000000010040f498: (GetAnyAddress.MyStruct) myStruct = { | |
| 0x000000010040f498: foo = 1 | |
| } | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment