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.
Explanation
Section titled “Explanation”خارجي(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), whilestrlenfrom C counts bytes (6): an Arabic letter is two bytes in UTF-8.
خارجي "m" داله جذر_c(س كسر64) كسر64 باسم "sqrt"خارجي داله طول_c(ن نص) طبيعي64 باسم "strlen"اطبع(جذر_c(2.0))اطبع("ميم بالبايتات: ", طول_c("ميم"), "، وبالأحرف: ", طول("ميم"))- 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.
خطر: م = احجز_خام(عدد32, 3) م[0] = 10 م[1] = 20 م[2] = 30 اطبع(م[0] + م[1] + م[2]) حرر(م)- 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-unsafeoption forbidsخطرentirely, and--no-ffiforbidsخارجي.
Exercise
Section titled “Exercise”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
خارجي داله abs_c(س عدد32) عدد32 باسم "abs"لكل ع في [-7, 0, 12]: اطبع(ع, " ← ", abs_c(عدد32(ع)))Common mistakes
Section titled “Common mistakes”A raw operation outside خطر:
م = احجز_خام(عدد64, 2)Exit code: 2
In the error catalog: E0414
See also
Section titled “See also”What is خطر? · The low-level layer · Calling C