コンテンツにスキップ

to_unsafe

型が `to_unsafe` メソッドを定義している場合、それを C に渡す際に、このメソッドによって返される値が渡されます。例えば

lib C
  fun exit(status : Int32) : NoReturn
end

class IntWrapper
  def initialize(@value)
  end

  def to_unsafe
    @value
  end
end

wrapper = IntWrapper.new(1)
C.exit(wrapper) # wrapper.to_unsafe is passed to C function which has type Int32

これは、C の型をラップした値に明示的に変換することなく、C の型のラッパーを定義するのに非常に便利です。

例えば、`String` クラスは `to_unsafe` を実装して `UInt8*` を返します。

lib C
  fun printf(format : UInt8*, ...) : Int32
end

a = 1
b = 2
C.printf "%d + %d = %d\n", a, b, a + b