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 類型的包裝器非常有用,而無需將它們顯式轉換為它們的包裝值。
例如,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