1

I have two variables of type "UnsafePointer<Float>" that should point to two C arrays of floats.

I already know how to access the value of the memory to which they point.

What I don't know how to do, is determine if they both refer to the same memory (i.e.: both point to the same address).

How does one check whether the memory addresses stored by two UnsafePointers are the same?

original_username
  • 2,398
  • 20
  • 24

1 Answers1

4

In Swift, UnsafePointer<T> conforms to the Comparable protocol, so you can simply compare the pointers with ==. Example: A C function

float *foo(void);

is mapped to Swift as

func foo() -> UnsafePointer<Float>

and the following code compiles, and tests if two subsequent calls to the function return the same pointer:

let p1 = foo()
let p2 = foo()
if p1 == p2 {
    println("equal")
}

As Joachim already said in a comment, a pointers value is the address of the memory it points to. So the pointers being equal means that they point to the same memory address.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • That doesn't compile, Martin "Function produces expected type Int, did you mean to call it with ()" I assume the Int is the memory address if I call it with braces, but I'd like to double-check. – original_username Jul 12 '14 at 10:35
  • 1
    @Charlesism: It was meant as an *example*. Of course `= ...` does not compile. You have to fill in your pointers. – Martin R Jul 12 '14 at 10:36