The Crystal standard library includes some pre-defined annotations:

Link

Tells the compiler how to link a C library. This is explained in the lib section.

Extern

Marking a Crystal struct with this attribute makes it possible to use it in lib declarations:

  1. @[Extern]
  2. struct MyStruct
  3. end
  4. lib MyLib
  5. fun my_func(s : MyStruct) # OK (gives an error without the Extern attribute)
  6. end

You can also make a struct behave like a C union (this can be pretty unsafe):

  1. # A struct to easily convert between Int32 codepoints and Chars
  2. @[Extern(union: true)]
  3. struct Int32OrChar
  4. property int = 0
  5. property char = '\0'
  6. end
  7. s = Int32OrChar.new
  8. s.char = 'A'
  9. s.int # => 65
  10. s.int = 66
  11. s.char # => 'B'

ThreadLocal

The @[ThreadLocal] attribute can be applied to class variables and C external variables. It makes them be thread local.

  1. class DontUseThis
  2. # One for each thread
  3. @[ThreadLocal]
  4. @@values = [] of Int32
  5. end

ThreadLocal is used in the standard library to implement the runtime and shouldn’t be
needed or used outside it.

Packed

Marks a C struct as packed, which prevents the automatic insertion of padding bytes between fields. This is typically only needed if the C library explicitly uses packed structs.

AlwaysInline

Gives a hint to the compiler to always inline a method:

  1. @[AlwaysInline]
  2. def foo
  3. 1
  4. end

NoInline

Tells the compiler to never inline a method call. This has no effect if the method yields, since functions which yield are always inlined.

  1. @[NoInline]
  2. def foo
  3. 1
  4. end

ReturnsTwice

Marks a method or lib fun as returning twice. The C setjmp is an example of such a function.

Raises

Marks a method or lib fun as potentially raising an exception. This is explained in the callbacks section.

CallConvention

Indicates the call convention of a lib fun. For example:

  1. lib LibFoo
  2. @[CallConvention("X86_StdCall")]
  3. fun foo : Int32
  4. end

The list of valid call conventions is:

  • C (the default)
  • Fast
  • Cold
  • WebKit_JS
  • AnyReg
  • X86_StdCall
  • X86_FastCall

They are explained here.

Flags

Marks an enum as a “flags enum”, which changes the behaviour of some of its methods, like to_s.