W3cubDocs

/Crystal 0.31

pointerof

The pointerof expression returns a Pointer that points to the contents of a variable or instance variable.

An example with a variable:

a = 1

ptr = pointerof(a)
ptr.value = 2

a #=> 2

An example with an instance variable:

class Point
  def initialize(@x : Int32, @y : Int32)
  end

  def x
    @x
  end

  def x_ptr
    pointerof(@x)
  end
end

point = Point.new 1, 2

ptr = point.x_ptr
ptr.value = 10

point.x #=> 10

Because pointerof involves pointers, it is considered unsafe.

To the extent possible under law, the persons who contributed to this workhave waived
all copyright and related or neighboring rights to this workby associating CC0 with it.
https://crystal-lang.org/docs/syntax_and_semantics/pointerof.html