struct Pointer(T)
- Pointer(T)
- Value
- Object
Overview
A typed pointer to some memory.
This is the only unsafe type in Crystal. If you are using a pointer, you are writing
unsafe code because a pointer doesn't know where it's pointing to nor how much memory
starting from it is valid. However, pointers make it possible to interface with C and
to implement efficient data structures. For example, both Array
and Hash
are
implemented using pointers.
You can obtain pointers in four ways: #new
, #malloc
, pointerof
, or by calling a C
function that returns a pointer.
pointerof(x)
, where x is a variable or an instance variable, returns a pointer to
that variable:
x = 1
ptr = pointerof(x)
ptr.value = 2
x # => 2
Use #value
to dereference the pointer.
Note that a pointer is falsey if it's null (if its address is zero).
When calling a C function that expects a pointer you can also pass nil
instead of using
Pointer.null
to construct a null pointer.
For a safe alternative, see Slice
, which is a pointer with a size and with bounds checking.
Included Modules
- Comparable(Pointer(T))