LEVIATHAN vd52e79c4 · d52e79c486

Standard Library

class Ptr

An opaque address of foreign (C) memory or code.

since 0.1.0-alpha.1linuxwindowswasm

Overview

A Ptr is a plain value: copying it copies the address, and two Ptrs are equal when their addresses are equal. The runtime never reads through it, frees it or keeps anything alive for it, so a Ptr can be stored in fields, arrays and maps and passed to threads freely; whether the memory behind it is still valid is the program's business, exactly as in C. Ptr has no ordering and no literal: make one with ffi::nullPtr() or ffi::ptr(addr), or receive one from a foreign function. Read and write the memory behind it through ffi::view(p, len), which returns a Block over those bytes.

Ptr? is the nullable form: at a foreign-function boundary None is passed as NULL and a returned NULL arrives as None.

Examples

Pointer arithmetic and printing

uses ffi;
use ffi;
use io::console;
Ptr p = ffi::ptr(4096);
Ptr q = p.offset(16);
console.writeln(q.toString());
console.writeln(q.addr() - p.addr());
console.writeln(ffi::nullPtr().isNull());
0x1010
16
true

Methods

addr

addr() -> int

The address as an integer.

Returns

The address, zero-extended to 64 bits.

Examples

The address as a number

uses ffi;
use ffi;
use io::console;
console.writeln(ffi::nullPtr().addr());
0

isNull

isNull() -> bool

Test whether this is the null address.

Returns

true when the address is 0.

Examples

The null address

uses ffi;
use ffi;
use io::console;
console.writeln(ffi::nullPtr().isNull());
true

offset

offset(int bytes) -> Ptr

The address bytes further on (or back, when negative).

No bounds are checked: the result is only an address.

Parameters

bytes
The distance in bytes.

Returns

The moved address.

Examples

Moving forward and back

uses ffi;
use ffi;
use io::console;
Ptr p = ffi::ptr(4096);
console.writeln(p.offset(16).addr());
console.writeln(p.offset(-16).addr());
4112
4080

toString

toString() -> string

The address in hexadecimal.

The text is 0x followed by lowercase hexadecimal digits with no padding; the null address is 0x0.

Returns

The address as text.

Examples

Printing an address

uses ffi;
use ffi;
use io::console;
console.writeln(ffi::nullPtr().toString());
console.writeln(ffi::nullPtr().offset(255).toString());
0x0
0xff

See also

  • view — A Block over len bytes of foreign memory starting at p.
  • nullPtr — The null address.