Printing a variable memory address in swift

前端 未结 15 1101
天涯浪人
天涯浪人 2020-11-28 01:16

Is there anyway to simulate the [NSString stringWithFormat:@\"%p\", myVar], from Objective-C, in the new Swift language?

For example:

le         


        
15条回答
  •  醉酒成梦
    2020-11-28 01:37

    The answer @Drew provide can only be used for class type.
    The answer @nschum provide can only be for struct type.

    However if you use the second method to get address of a array with value type element. Swift will copy the whole array because in Swift array is copy-on-write and Swift can't make sure it behave this way once it pass control over to C/C++ (Which is trigger by using & to get address). And if you use first method instead , it will automatically convert Array to NSArray which is surely something we don't want.

    So the most simple and unified way I found is using lldb instruction frame variable -L yourVariableName.

    Or you can combine their answers:

    func address(o: UnsafePointer) {
        let addr = unsafeBitCast(o, Int.self)
        print(NSString(format: "%p", addr))
    }
    
    func address(o: T) -> String{
        let addr = unsafeBitCast(o, Int.self)
        return NSString(format: "%p", addr) as String
    }
    

提交回复
热议问题