Raw Pointers

How Bramble represents memory addresses, pointers to locations in memory, and the manipulation of memory directly.

How Bramble represents memory addresses, pointers to locations in memory, and the manipulation of memory directly.

Overview

In order to support low level memory operations and full FFI, Bramble must have the ability to operate on memory directly through pointers and pointer manipulation. As with many modern languages, Bramble wants users to avoid using these tools, except in the cases where they are the only or clearly correct option. To this end, the operations to get raw pointers are tedious and typing heavy and will, eventually, have to happen within an unsafe expression block.

Pointer Types

There are two raw pointer types: *const T and *mut T. *const T is a pointer to an immutable location in memory: dereferencing this pointer will let you read from this location in memory but it will not let you write to this location. *mut T is a pointer to a mutable location in memory: dereferencing this pointer will let you read from this location and write to this location.

Creating a Pointer

To create a pointer, use the address of operators: @const or @mut. @const will return a *const pointer to the operand. @mut will return a *const pointer to the operand, but it can only be applied to mutable values.

The operand of @const and @mut must be an addressable expression. This is an expression that resolves to a value that has a location in memory, generally this is a variable.

Dereferencing a Pointer

To read from or write to the location through a raw pointer, you need to use the dereference operator: ^. To read from a memory location you can use the ^pointer in any expression where the underyling type would be valid. To write to a memory location, use mut ^p := ....

Pointer Arithmetic

To get addresses that are offsets from a given pointer, use the @ in its binary form: p@-2 will return a new address which is equivalent to p - 2 * (size_of(T)) where T is the type of the value that p points to.


Last modified February 10, 2022: Polishing language (6c7ee7b)