Last active
July 9, 2024 03:38
-
-
Save nyg/b6a80bf79e72599230c312c69e963e60 to your computer and use it in GitHub Desktop.
Get the memory address of both class and structure instances in Swift.
This file contains 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 | |
struct MemoryAddress<T>: CustomStringConvertible { | |
let intValue: Int | |
var description: String { | |
let length = 2 + 2 * MemoryLayout<UnsafeRawPointer>.size | |
return String(format: "%0\(length)p", intValue) | |
} | |
// for structures | |
init(of structPointer: UnsafePointer<T>) { | |
intValue = Int(bitPattern: structPointer) | |
} | |
} | |
extension MemoryAddress where T: AnyObject { | |
// for classes | |
init(of classInstance: T) { | |
intValue = unsafeBitCast(classInstance, to: Int.self) | |
// or Int(bitPattern: Unmanaged<T>.passUnretained(classInstance).toOpaque()) | |
} | |
} | |
/* Testing */ | |
class MyClass { let foo = 42 } | |
var classInstance = MyClass() | |
let classInstanceAddress = MemoryAddress(of: classInstance) // and not &classInstance | |
print(String(format: "%018p", classInstanceAddress.intValue)) | |
print(classInstanceAddress) | |
struct MyStruct { let foo = 1 } // using empty struct gives weird results (see StackOverflow comments) | |
var structInstance = MyStruct() | |
let structInstanceAddress = MemoryAddress(of: &structInstance) | |
print(String(format: "%018p", structInstanceAddress.intValue)) | |
print(structInstanceAddress) | |
/* output | |
0x0000000101916c80 | |
0x0000000101916c80 | |
0x00000001005e3000 | |
0x00000001005e3000 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment