Skip to content

Instantly share code, notes, and snippets.

@nyg
Last active October 12, 2023 07:42
Show Gist options
  • Star 34 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • Save nyg/b6a80bf79e72599230c312c69e963e60 to your computer and use it in GitHub Desktop.
Save nyg/b6a80bf79e72599230c312c69e963e60 to your computer and use it in GitHub Desktop.
Get the memory address of both class and structure instances in Swift.
// 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