Skip to content
العربية

21. «خطر» (unsafe) and calling C

To call a function from a C library, and to know what can only be written inside a خطر block, and why.

  • خارجي (extern) declares a function from a C library with explicit C types; then you call it like any function. At compile time, the compiler checks that the symbol exists.
  • طول("ميم") counts characters (3), while strlen from C counts bytes (6): an Arabic letter is two bytes in UTF-8.
Two functions from C
خارجي "m" داله جذر_c(س كسر64) كسر64 باسم "sqrt"
خارجي داله طول_c(ن نص) طبيعي64 باسم "strlen"
اطبع(جذر_c(2.0))
اطبع("ميم بالبايتات: ", طول_c("ميم"), "، وبالأحرف: ", طول("ميم"))
Output recorded from the compilermeem 17_خارجي.م · meem 0.17.3+434e13f
1.4142135623730951ميم بالبايتات: 6، وبالأحرف: 3
  • Raw memory (احجز_خام), raw pointer indexing, and switching checks off (بلا_فحص) can only be written inside خطر:. There the compiler does not check bounds, and mistakes are your responsibility.
Raw memory inside خطر
خطر:
م = احجز_خام(عدد32, 3)
م[0] = 10
م[1] = 20
م[2] = 30
اطبع(م[0] + م[1] + م[2])
حرر(م)
Output recorded from the compilermeem 17_خطر.م · meem 0.17.3+434e13f
60
  • A beginner does not need it: lists, dictionaries and the standard modules are enough for most programs. And خطر keeps whatever might corrupt memory in blocks you can see and review.
  • The --no-unsafe option forbids خطر entirely, and --no-ffi forbids خارجي.

Declare the function abs from the C library (it takes and returns عدد32), and print its absolute value for -7, 0 and 12.

Show the solution
Solution
خارجي داله abs_c(س عدد32) عدد32 باسم "abs"
لكل ع في [-7, 0, 12]:
اطبع(ع, " ← ", abs_c(عدد32(ع)))
Output recorded from the compilermeem 17_حل.م · meem 0.17.3+434e13f
-7 ← 70 ← 012 ← 12

A raw operation outside خطر:

Causes the error
م = احجز_خام(عدد64, 2)
Output recorded from the compilermeem 17_بلا_خطر.م · meem 0.17.3+434e13f
​[خطأ دلالي E0414] سطر 1:5 - 'احجز_خام' لا تُكتب إلا داخل منطقة 'خطر'   1 | م = احجز_خام(عدد64, 2)     |     ^~~~~~~~  تلميح: ضعها في كتلة  خطر:  أو في دالة معرَّفة بـ  خطر داله ...

Exit code: 2

In the error catalog: E0414

What is خطر? · The low-level layer · Calling C