to_unsafe

If a type defines a to_unsafe method, when passing it to C the value returned by this method will be passed. For example:

  1. lib C
  2. fun exit(status : Int32) : NoReturn
  3. end
  4. class IntWrapper
  5. def initialize(@value)
  6. end
  7. def to_unsafe
  8. @value
  9. end
  10. end
  11. wrapper = IntWrapper.new(1)
  12. C.exit(wrapper) # wrapper.to_unsafe is passed to C function which has type Int32

This is very useful for defining wrappers of C types without having to explicitly transform them to their wrapped values.

For example, the String class implements to_unsafe to return UInt8*:

  1. lib C
  2. fun printf(format : UInt8*, ...) : Int32
  3. end
  4. a = 1
  5. b = 2
  6. C.printf "%d + %d = %d\n", a, b, a + b