5.1.22. Unsafe and Pointers

This tutorial covers daslang’s unsafe block for opt-in low-level operations: raw pointers, addr/deref, null handling, pointer arithmetic, and reinterpret casts.

5.1.22.1. unsafe blocks

unsafe { ... } enables pointer operations and other low-level features that are normally disallowed:

var x = 42
unsafe {
    var p : int? = addr(x)
    *p = 100
}

Use unsafe(expr) for a single expression:

let p = unsafe(addr(x))

5.1.22.2. addr and deref

addr(x) returns a pointer T? to a local variable. *p (or deref(p)) follows the pointer:

unsafe {
    var p = addr(x)
    print("{*p}\n")   // prints value of x
    *p = 999          // modifies x through pointer
}

5.1.22.3. Null pointers

Dereferencing a null pointer causes a panic inside try/recover:

var np : int? = null
try {
    print("{*np}\n")
} recover {
    print("caught null deref\n")
}

5.1.22.4. Pointer arithmetic

Pointers can index into contiguous memory (e.g., arrays):

unsafe {
    var arr = [10, 20, 30]
    var p = addr(arr[0])
    print("{p[0]}, {p[1]}, {p[2]}\n")  // 10, 20, 30
}

5.1.22.5. reinterpret

reinterpret performs a raw bit cast between types of the same size:

let f = 1.0
let bits = unsafe(reinterpret<int> f)
print("{bits:x}\n")  // 3f800000

Warning

unsafe does not propagate into lambdas or generators. Each lambda/generator body needs its own unsafe block if needed.

See also

Unsafe in the language reference.

Full source: tutorials/language/22_unsafe.das

Next tutorial: String Builder and Formatting