How do I get the original binary binary pattern from an unsafe Swift pointer?

You can build UnsafePointer

from an integer like:

let ptr = UnsafePointer<Void>(bitPattern: 123)


But how can you get that integer bit pattern (123 in this case) back from the pointer?

Why would you do this?

(Added in response to some comments in which I assumed I was not using pointers correctly.)

This is not what you usually do, and the above pointer is not really a pointer to anything. If the program dereferences it, it will crash.

Some low level C APIs use void *

some arbitrary data to denote. This is the C version of generic types. For example, imagine a stack data structure in C, with an API like

Stack *create_stack();
void stack_push(Stack *stack, void *element);
void *stack_pop(Stack *stack);


Usually, you have to pass pointers to a bunch of allocated data, but you can say that you want a stack of 64-bit integers, and you know that pointers on your system are 64 bits. You can store integers directly on your stack and avoid heap allocation ...

Stack *myStack = create_stack();
long elt = 123;
stack_push(myStack, (void*)elt);
elt = (long)stack_pop(myStack);


I'm dealing with an API like this, but more complex (for multi-purpose tessellation).


source to share

2 answers

I found the answer on another forum. Use unsafeBitCast


let ptr = UnsafePointer<Void>(bitPattern: 123)
let x: Int64 = unsafeBitCast(ptr, Int64.self)
// x == 123




While unsafeBitCast

working, the natural solution is Swift 4

let ptr = UnsafePointer<Void>(bitPattern: 123)
let x = Int(bitPattern: ptr)


(Note that this Int

is the same size as the pointer on 32-bit and 64-bit platforms.)

Both Int

and UInt

have bitPattern:

initializers for multiple types of indexes:

  • UnsafePointer<_>?

  • UnsafeRawPointer<_>?

  • UnsafeMutablePointer<_>?

  • UnsafeMutableRawPointer<_>?

  • OpaquePointer?

  • ObjectIdentifier



All Articles