跳至內容

內建的註解

Crystal 標準函式庫包含一些預定義的註解

告訴編譯器如何連結 C 函式庫。這在 lib 章節中有說明。

Extern

使用此註解標記 Crystal 結構,使其可以在 lib 宣告中使用

@[Extern]
struct MyStruct
end

lib MyLib
  fun my_func(s : MyStruct) # OK (gives an error without the Extern annotation)
end

您也可以讓結構的行為像 C 聯合 (這可能非常不安全)

# A struct to easily convert between Int32 codepoints and Chars
@[Extern(union: true)]
struct Int32OrChar
  property int = 0
  property char = '\0'
end

s = Int32OrChar.new
s.char = 'A'
s.int # => 65

s.int = 66
s.char # => 'B'

ThreadLocal

@[ThreadLocal] 註解可以應用於類別變數和 C 外部變數。它使它們成為執行緒本地變數。

class DontUseThis
  # One for each thread
  @[ThreadLocal]
  @@values = [] of Int32
end

ThreadLocal 在標準函式庫中用於實作執行時期,不應該在外部需要或使用它。

Packed

C 結構 標記為已封裝,這會阻止在欄位之間自動插入填充位元組。這通常只有在 C 函式庫明確使用已封裝結構時才需要。

AlwaysInline

給予編譯器提示,永遠將方法內聯

@[AlwaysInline]
def foo
  1
end

NoInline

告訴編譯器永遠不要內聯方法呼叫。如果方法產生值,則沒有效果,因為產生值的方法永遠都會內聯。

@[NoInline]
def foo
  1
end

ReturnsTwice

將方法或 lib fun 標記為回傳兩次。C setjmp 就是這樣一個函式的範例。

Raises

將方法或 lib fun 標記為可能引發例外。這在 callbacks 章節中有說明。

CallConvention

指示 lib fun 的呼叫慣例。例如

lib LibFoo
  @[CallConvention("X86_StdCall")]
  fun foo : Int32
end

有效的呼叫慣例清單為

  • C (預設)
  • Fast
  • Cold
  • WebKit_JS
  • AnyReg
  • X86_StdCall
  • X86_FastCall

它們在 這裡 有說明。

Flags

enum 標記為「旗標列舉」,這會改變其某些方法 (例如 to_s) 的行為。