annotation Extern
Overview
Marks a struct type for external use, allowing it to be used in lib
declarations.
This prevents the compiler from optimizing the layout of the struct, and ensures it matches the C ABI.
@[Extern]
struct MyStruct
property x = 0
property y = 0
end
lib MyLib
fun my_func(s : MyStruct) # would error without the Extern annotation
end
The union: true argument makes the struct behave like a C union, where all
instance variables share the same memory location (this can be unsafe):
@[Extern(union: true)]
struct Int32OrChar
property int = 0
property char = '\0'
end
s = Int32OrChar.new
s.char = 'A'
s.int # => 65
NOTE The Crystal book has a section about Built-in Annotations: Extern.