Created
September 1, 2022 07:13
-
-
Save tgnivekucn/225ec01a06603646b1dd11c3c9cf7c1d to your computer and use it in GitHub Desktop.
Get memory address of the object(p.s. class or struct)
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
import Foundation | |
// Ref: https://stackoverflow.com/questions/24058906/printing-a-variable-memory-address-in-swift | |
// Author: nyg (profile: https://stackoverflow.com/users/5536516/nyg) | |
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()) | |
} | |
} | |
// Below is testing code | |
class MyClass { | |
let foo = 42 | |
let tmp = 55 | |
} | |
struct MyStruct { let foo = 3 } // using empty struct gives weird results (see comments) | |
var classInstance = MyClass() | |
let referencePointerOfClassInstance = UnsafeMutablePointer<MyClass>(&classInstance) | |
let t1ClassInstance = classInstance | |
let t2ClassInstance = MyClass() | |
print("classInstance address: \(MemoryAddress(of: classInstance))") | |
print("t1ClassInstance address: \(MemoryAddress(of: t1ClassInstance))") | |
print("t2ClassInstance address: \(MemoryAddress(of: t2ClassInstance))") | |
var structInstance = MyStruct() | |
let referencePointerOfStructInstance = UnsafePointer<MyStruct>(&structInstance) | |
var t1StructInstance = structInstance | |
var t2StructInstance = MyStruct() | |
print("structInstance address: \(MemoryAddress(of: &structInstance))") | |
print("t1StructInstance address: \(MemoryAddress(of: &t1StructInstance))") | |
print("t2StructInstance address: \(MemoryAddress(of: &t2StructInstance))") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment