Low-Level Programming

36.1 Pointers

int x = 10;
int* p = &x;
*p = 20;
int[] arr = [1, 2, 3];
int* q = arr.ptr;
writeln(*(q + 1));                 // pointer arithmetic (@system only)
int[] s = q[0 .. 3];               // pointer → slice
void* vp = cast(void*) p;
ubyte* bytes = cast(ubyte*) &x;

36.2 Inline Assembly

// DMD (x86 Intel syntax)
int add(int a, int b)
{
    asm
    {
        mov EAX, a;
        add EAX, b;
    }
    // the result is returned in EAX
}

// LDC/GDC: GCC-style extended asm
version (LDC)
{
    import ldc.llvmasm;
    ulong rdtsc() { return __asm!ulong("rdtsc; shl $$32, %rdx; or %rdx, %rax", "={rax},~{rdx}"); }
}

36.3 SIMD and Intrinsics

core.atomic (Module 37), core.volatile, core.stdc.* (the C standard library), core.sys.posix.* and core.sys.windows.* (OS APIs), core.bitop, core.checkedint (overflow-checked arithmetic), std.bitmanip (endianness: nativeToBigEndian, read/write, BitArray).

import core.simd;
float4 a = [1, 2, 3, 4];
float4 b = 2;
float4 c = a * b + a;
writeln(c.array);

// Portable intrinsics: the `intel-intrinsics` DUB package (SSE/AVX names on any compiler)
import core.bitop : popcnt, bsf, bsr, bswap, rol, ror;
writeln(popcnt(0b1011u), bsr(16u));

36.4 Memory Layout

align(16) struct Vec4 { float x, y, z, w; }
struct Packed { align(1): ubyte a; int b; }     // packed members
writeln(Vec4.alignof, " ", Packed.sizeof, " ", Packed.b.offsetof);