Pointer
is a data type for representing C pointers.
address
(Fn [(Ref a b)] (Ptr a))
returns the memory address of a reference. Equivalent to the &
operator when placed before a variable in C.
free
(Fn [(Ptr a)] ())
Free a pointer, deallocating the memory associated with it.
Carp's borrow checker handles deallocation automatically for managed types. The Ptr type is unmanaged, so pointers allocated with functions such as Pointer.unsafe-alloc
need to be deallocated manually using this function.
Users need to manually verify that this operation is safe.
(let-do [x (Pointer.unsafe-alloc @"c")]
(Pointer.set x @"carp")
(println* (Pointer.to-value x))
(Pointer.free x))
to-ref
(Fn [(Ptr a)] (Ref a b))
converts a pointer to a reference type.
The user will have to ensure themselves that this is a safe operation.
to-value
(Fn [(Ptr a)] a)
converts a pointer to a value.
The user will have to ensure themselves that this is a safe operation.
unsafe-alloc
(Fn [a] (Ptr a))
Allocate a new pointer to the value a
.
This pointer won't be managed by Carp's borrow checker and will cause memory leaks unless explicitly freed using Pointer.free
.
See Unsafe.leak
if you want to prevent Carp's automatic memory management from deallocating a value without performing an allocation.
(let-do [x (Pointer.unsafe-alloc @"c")]
(Pointer.set x @"carp")
(println* (Pointer.to-value x))
(Pointer.free x))
unsafe-set
(Fn [(Ptr a), b] ())
Sets the value of a pointer to a value of any type. The user will have to ensure this operation is safe.