> Agent-readable docs index: /llms.txt. Download /docs.zip to grep all markdown files locally.

---
title: FFI Crash Course
description: An in-depth introduction to FFI - pointers, memory, type punning, signatures, interfaces, and casting - for Lua developers.
icon: cpu
sidebar_position: 2
---

# FFI Crash Course

An introduction to FFI for Lua developers: allocate C data, work with pointers, and understand native function bindings in the current CS2 API.

<Info>
  The first sections use **illustrative C fragments**, not complete programs. The Lua examples assume the FFI setup below; run each example separately unless a section says to continue the preceding example.
</Info>

## What is FFI?

FFI - the **Foreign Function Interface** - is an interface between different languages that lets them interact. It's generally used to create *bindings* to C/C++ libraries from higher-level languages like Python, Ruby, and - most importantly for us - Lua. Bindings are just functions in the high-level language that reach down into the low-level libraries and call their functions.

In practice, FFI is most commonly used to provide an interface into the game process's memory. This lets you interact directly with the game - such as calling its functions - without relying on a middleman like the Lua API. Because FFI bridges Lua and C, using it requires some knowledge of low-level memory and how languages like C interact with it.

## ctype and cdata

API declaration labels distinguish the C type object you call from the C values it creates:

| Label   | Meaning                                                                                         | Projection example                                   |
| ------- | ----------------------------------------------------------------------------------------------- | ---------------------------------------------------- |
| `ctype` | A C type object. Call it as a constructor to create a value.                                    | `projection.Rect`                                    |
| `cdata` | A C value, such as a struct, scalar, or pointer. Its type determines its fields and operations. | The `ProjectionRect` returned by `projection.Rect()` |

`namespace projection` groups the projection helpers. Within that namespace,
`ctype projection.Rect` documents the constructor, while `cdata ProjectionRect`
documents the values returned by it. A ctype can also expose helper functions and constants.

`projection.Rect` is already available in the CS2 API:

```lua
local Rect = projection.Rect -- ctype: the constructor
local rect = Rect()          -- cdata: a rectangle value
print(rect.m_vMinBounds.x)
```

`ffi.typeof` returns a ctype object; calling it or passing it to `ffi.new` creates
cdata values. Technically, a ctype is itself a special kind of cdata, so Lua's
`type()` returns `"cdata"` for both the constructor and its values. These labels
describe their roles, not two distinct results of `type()`.
See the [LuaJIT FFI glossary](https://luajit.org/ext_ffi_api.html).

Neither label establishes ownership or lifetime. A cdata value may be an independent
copy, or a pointer/reference to storage owned by the game. Follow each API's copy
and borrowed-reference documentation before retaining or modifying a value.

## Memory and how languages interact with it

In low-level languages like C, memory can be interacted with directly. C gives us **pointers** for this - essentially memory addresses that ideally point to a specific variable. That variable can be of any type (integer, float, string, or even another pointer) and contain any value.

### Safe and unsafe pointers

A pointer stores an address. A **null pointer** represents no object, but a non-null address can still be invalid or refer to an object that has already been freed. Before dereferencing, you need to know which allocation owns the bytes, their type, and how long they remain alive.

<Tabs>
  <Tab title="Safe pointer" icon="shield-check">
    ```c
    float floating_point = 100.f;             // A normal variable.
    float* floating_pointer = &floating_point; // & takes its address.
    ```

    `floating_pointer` holds the address of `floating_point` and remains valid while that variable is alive.
  </Tab>

  <Tab title="Unsafe pointer" icon="triangle-alert">
    ```c
    char* our_string = (char*)0x1234;
    char first_character = *our_string;
    ```

    We assign an arbitrary address instead of one we retrieved from something known to exist. We can't guarantee `0x1234` points to a real string - it almost certainly doesn't.
  </Tab>
</Tabs>

<Warning>
  Dereferencing the invented address above is undefined behavior and can crash the application. The `&` operator takes an object's address; it does not extend that object's lifetime.
</Warning>

### Reading memory and dereferencing

**Dereferencing** is the act of reading the memory at the address stored in a pointer. In C you use the `*` operator before the variable name:

```c
float original_value = *floating_pointer;
```

If `floating_pointer` held the address of `floating_point`, then `original_value` now contains `100.f`.

### Why unsafe pointers?

FFI can allocate its own objects with `ffi.new`, or interpret an address owned by native code. For native addresses, the caller must establish the layout and lifetime. The CS2 API provides [`memory.FindPattern`](/cs2/api_reference/engine/memory#memory-FindPattern) for scanning and [`memory.CreateInterface`](/cs2/api_reference/engine/memory#memory-CreateInterface) for interface lookup. Prefer typed APIs such as [`entity`](/cs2/api_reference/engine/entity) when they already expose the operation you need.

## Type punning

Type punning is the act of bypassing the type system to reinterpret the same bytes as a different type. Suppose a region of memory at `0x405060` holds the start of an XML string. We can read its first 4 bytes as a 4-byte integer instead:

```c
int* int_pointer = (int*)0x405060;
int first_4_bytes = *int_pointer;

// The same, tied into one line:
int first_4_bytes = *(int*)0x405060;
```

The bracketed type before the address is a **cast** - telling the language how to interpret that address.

<Tip>
  **Memory is just a massive sequence of bytes**, and it can be represented however you want. This flexibility is exactly where a lot of the unsafety comes from.
</Tip>

## Pointer arithmetic

Pointer arithmetic works like normal arithmetic (`+` and `-` only - no multiply/divide), but it accounts for the **size of the pointer's type**. Every type has a size, so adding `1` to a pointer advances it by one element, not one byte.

```c
int our_array[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
int* our_array_ptr = our_array; // The array converts to a pointer here.
int our_2nd_value = *(our_array + 1);
```

<Note>
  On CS2's Windows x64 platform, `int` is 4 bytes. If `our_array` starts at `0x14001f068`, then `our_array + 1` is `0x14001f06C`: the address advances by the element size.
</Note>

## Getting practical with FFI

Lua isn't really intended to be a low-level language, so it lacks some operators C provides. The following sections show how to achieve what we need anyway.

### Getting started

Declare `ffi` in your [extension manifest](/cs2/api_reference/extensions/requirements):

```json extension.json
{
  "language": "lua",
  "requirements": ["ffi"]
}
```

Then load it in `main.lua`:

```lua
local ffi = require("ffi")
```

The local `ffi` variable is available in that Lua file. Add the same `require` line to other files or standalone examples that use it.

<Tip>
  The [`FFI reference`](/cs2/api_reference/lua/ffi) describes the exposed library. Declaring `ffi` also enables `memory.CreateInterface`, `memory.FindPattern`, `memory.BindVirtual`, `memory.VirtualThunk`, and `memory.BindPattern`. Those functions are `nil` without the requirement.
</Tip>

### Dereferencing in Lua

Lua has no dereference operator like C's `*`. FFI pointer indexing reads an element at an offset: `[0]` reads the pointed-to element, and `[1]` reads the next one.

```lua
local values = ffi.new("int[3]", {10, 20, 30})
local pointer = ffi.cast("int*", values)
print(pointer[0], pointer[1]) -- 10, 20
assert(pointer[2] == values[2]) -- Keep the owning array alive during use.
```

An array owns its elements; a pointer stores an address. Casting the array to a pointer does not transfer ownership or keep the array alive.

### Signatures and signature scanning

[`memory.FindPattern(module, pattern[, find_all])`](/cs2/api_reference/engine/memory#memory-FindPattern) scans a loaded module for a byte pattern. It normally returns the first matching address as `userdata`. The pattern uses **space-separated hex bytes**, and `?` marks a **wildcard** byte:

```lua
-- Format example only; this is not a verified function signature.
local pattern = "48 8B ? ?"
```

Wildcards can cover changing operands such as relative addresses. A match only identifies bytes: it does not prove that the address is a function, establish its prototype, or resolve a relative instruction operand.

The helper below accepts a module and pattern you have verified against the current game build. It performs no scan until you call it with those inputs:

```lua
local function find_unique(module, verified_pattern)
  assert(memory.FindPattern, "Declare ffi in extension.json")
  local matches = {memory.FindPattern(module, verified_pattern, true)}
  assert(#matches == 1, "Expected exactly one pattern match")
  return matches[1]
end
```

<Tip>
  With `find_all = true`, the scanner returns every match in ascending address order as separate return values. No match produces no return values, so the table above is empty. Full scans cost more than first-match scans. Revalidate patterns, layouts, and function prototypes after game updates.
</Tip>

### The interface system

Source2 modules export interfaces identified by version strings. [`memory.CreateInterface(module, interface)`](/cs2/api_reference/engine/memory#memory-CreateInterface) returns an interface pointer or `nil`. This example checks an interface name used by the current API sources without calling any virtual functions:

```lua
assert(memory.CreateInterface, "Declare ffi in extension.json")
local instance = memory.CreateInterface("engine2.dll", "Source2EngineToClient001")
if instance ~= nil then
  print("Engine interface available")
else
  print("Engine interface unavailable in this build")
end
```

<Info>
  Check an interface result before casting. A null FFI pointer is truthy in Lua: `ffi.cast("void*", nil) or error(...)` does not detect it. Compare a typed pointer with `nil` to test for null. A non-null result still does not validate its type or lifetime.
</Info>

### Casting

Casting via `ffi.cast` tells Lua how to interpret a value; it does not validate the address. This example casts an allocation owned by the script, writes through the pointer, then reads the owning array:

```lua
local values = ffi.new("double[2]", {1.5, 2.5})
local pointer = ffi.cast("double*", values)
pointer[1] = 3.5
print(values[0], values[1]) -- 1.5, 3.5
```

<AccordionGroup>
  <Accordion title="Worked example: wrapping a live entity pointer" icon="code" defaultOpen>
    Use a pointer returned by a live entity rather than guessing which native function returns one. Run this while connected to a game; the lookup can return `nil` before a pawn exists.

    ```lua
    local pawn = entity.GetLocalPlayerPawn()
    if pawn then
      local instance = pawn:GetInstance()
      local wrapped = entity.WrapInstance(instance)
      if wrapped then print("Resolved entity:", wrapped:GetClassName()) end
    end
    ```
  </Accordion>
</AccordionGroup>

### Binding native functions

A virtual table stores native function pointers. Calling one requires the current slot, complete C prototype, and a live compatible instance. The following helpers reduce repeated binding code:

| Helper                                                                                                         | Instance handling                                                            |
| -------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- |
| [`memory.BindVirtual(module, interface, index, ...)`](/cs2/api_reference/engine/memory#memory-BindVirtual)     | Resolves the interface and binds it to the returned function.                |
| [`memory.VirtualThunk(index, ...)`](/cs2/api_reference/engine/memory#memory-VirtualThunk)                      | The returned function takes the instance as its first argument on each call. |
| [`memory.BindPattern(module, interface, signature, ...)`](/cs2/api_reference/engine/memory#memory-BindPattern) | Resolves the interface and function pattern, then binds the instance.        |

The trailing arguments describe the function type as accepted by `ffi.typeof`. These helpers cannot discover the correct slot or prototype for you. Use a current typed API such as [`engine.GetScreenSize`](/cs2/api_reference/engine/engine#engine-GetScreenSize) when it already covers the task.

## Calling WinAPI

`ffi.C` is the **default C library namespace**. On Windows it includes the default C runtime and kernel32 exports. Use `ffi.load` for other libraries, such as user32. `ffi.cdef` declares a prototype; it does not load a DLL or make every Windows function available through `ffi.C`.

<Steps>
  <Step title="Declare the function" icon="file-code">
    Use `ffi.cdef` once to tell FFI the function's C prototype. Match the WinAPI signature exactly - argument types and return type.

    ```lua
    local ffi = require("ffi")

    ffi.cdef[[
        short GetAsyncKeyState(int vKey);
        unsigned long GetTickCount(void);
    ]]
    local user32 = ffi.load("user32")
    ```
  </Step>

  <Step title="Call through the library namespace" icon="terminal">
    Continue the preceding code. `GetAsyncKeyState` belongs to user32; `GetTickCount` is available through `ffi.C`.

    ```lua
    -- VK_LBUTTON = 0x01. The high bit is set while the key is down.
    if bit.band(user32.GetAsyncKeyState(0x01), 0x8000) ~= 0 then
      print("left mouse is held")
    end

    local uptime_ms = ffi.C.GetTickCount()
    ```
  </Step>
</Steps>

<Warning>
  A `cdef` prototype is a **promise**, not a check. Incorrect argument or return types can corrupt memory or crash the game. Verify the declaration against the Windows API reference.
</Warning>

### Strings and wide strings

WinAPI comes in ANSI (`...A`) and wide/UTF-16 (`...W`) variants. Lua strings map directly to `const char*` for the `A` variants; for `W` variants you must build a wide buffer yourself.

<Tabs items={["ANSI variant", "Wide variant"]}>
  <Tab title="ANSI variant">
    ```lua
    local user32 = ffi.load("user32")
    ffi.cdef[[
        int MessageBoxA(void* hWnd, const char* text, const char* caption, unsigned int type);
    ]]

    -- 0x40 = MB_ICONINFORMATION. Lua strings pass straight through as const char*.
    user32.MessageBoxA(nil, "Hello from FFI!", "Neverlose", 0x40)
    ```
  </Tab>

  <Tab title="Wide variant">
    ```lua
    local user32 = ffi.load("user32")
    ffi.cdef[[
        int MultiByteToWideChar(unsigned int cp, unsigned long flags,
            const char* str, int cb, wchar_t* wide, int cch);
        int MessageBoxW(void* hWnd, const wchar_t* text, const wchar_t* caption, unsigned int type);
    ]]

    -- Convert a UTF-8 Lua string into a wchar_t buffer (CP_UTF8 = 65001).
    local function to_wide(s)
      local len = ffi.C.MultiByteToWideChar(65001, 0, s, -1, nil, 0)
      assert(len > 0, "UTF-8 conversion failed")
      local buf = ffi.new("wchar_t[?]", len)
      assert(ffi.C.MultiByteToWideChar(65001, 0, s, -1, buf, len) > 0,
        "UTF-8 conversion failed")
      return buf
    end

    user32.MessageBoxW(nil, to_wide("Wide text"), to_wide("Neverlose"), 0x40)
    ```
  </Tab>
</Tabs>

<Tip>
  Use `ffi.new` to allocate C buffers (`ffi.new("char[?]", size)`), `ffi.string(ptr[, len])` to read a C string back into Lua, and `ffi.sizeof(type)` when an API needs a struct size. These are the building blocks for any output-parameter WinAPI call.
</Tip>

### Output parameters

Many WinAPI functions return data through pointer arguments. Allocate a one-element array with `ffi.new`, pass it, then read index `[0]`:

```lua
ffi.cdef[[
    int QueryPerformanceCounter(int64_t* lpPerformanceCount);
]]

local counter = ffi.new("int64_t[1]")  -- A pointer to one int64_t.
assert(ffi.C.QueryPerformanceCounter(counter) ~= 0, "Counter unavailable")
print("perf counter:", counter[0])
```

<Note>
  For wall-clock time and scheduling, use [`time.GetEpochMilliseconds`](/cs2/api_reference/runtime/time#time-GetEpochMilliseconds), [`time.GetUnixTime`](/cs2/api_reference/runtime/time#time-GetUnixTime), and [`time.Schedule`](/cs2/api_reference/runtime/time#time-Schedule). The clock functions return boxed `int64_t` values; scheduling delays use seconds. Epoch time can jump when the system clock changes, so it is not a monotonic performance counter.
</Note>

## Power features

`ffi` is more than `ffi.cast` - these are the parts that turn it into a real metaprogramming tool. The subsections run from everyday building blocks to the rarer, more advanced corners.

### Richer C declarations

`ffi.cdef` understands far more than plain structs.

<Tabs>
  <Tab title="enum" icon="list-ordered">
    ```lua
    ffi.cdef[[ enum { DOCS_READY = 1, DOCS_VISIBLE = 2 }; ]]

    -- Enum constants are available on ffi.C:
    local flags = 3
    print(bit.band(flags, ffi.C.DOCS_READY) ~= 0) -- true
    ```
  </Tab>

  <Tab title="union" icon="layers">
    ```lua
    -- A union reinterprets the same bytes - type punning without pointers:
    ffi.cdef[[ typedef union { float f; uint32_t i; } fi_t; ]]

    local u = ffi.new("fi_t"); u.f = 1.0
    print(bit.tohex(u.i))   -- 3f800000  (the IEEE-754 bits of 1.0)
    ```
  </Tab>

  <Tab title="bitfields" icon="binary">
    ```lua
    -- Pack flags into exact bit widths:
    ffi.cdef[[ struct Bits { unsigned int a:1, b:7, c:24; }; ]]

    local b = ffi.new("struct Bits")
    b.a = 1; b.b = 100
    ```
  </Tab>

  <Tab title="packed / aligned" icon="box">
    ```lua
    -- Disable padding, or force alignment, with GCC attributes:
    ffi.cdef[[
      struct __attribute__((packed)) Raw { uint8_t tag; uint32_t value; };
      struct __attribute__((aligned(16))) Vec4 { float x, y, z, w; };
    ]]
    ```
  </Tab>

  <Tab title="variadic" icon="ellipsis">
    ```lua
    ffi.cdef[[ int printf(const char *fmt, ...); ]]

    -- Pass explicit cdata for the variadic args (float is promoted to double):
    ffi.C.printf("hp=%d\n", ffi.new("int", 100))
    ```
  </Tab>
</Tabs>

### Constructors and initialization

A ctype from `ffi.typeof` is **callable** - use it as a fast constructor, and initialize structs/arrays many ways:

```lua
local Pt = ffi.typeof("struct { double x, y; }")

local a = Pt(1, 2)                       -- positional
local b = Pt{ x = 1, y = 2 }            -- by field name
local arr = ffi.new("int[3]", {1, 2, 3}) -- array from a table
ffi.new("int[10]")                       -- zero-filled
```

### 64-bit integers

Numbers above 2^53 lose precision as Lua doubles. Use the `LL` / `ULL` suffixes (or `int64_t` cdata) to keep full width - handy for addresses, handles, and timestamps:

```lua
local a = 0x140000000LL    -- signed 64-bit literal
local b = 5ULL             -- unsigned 64-bit literal
print(a + 1)               -- 5368709121LL  (exact, boxed as cdata)
```

<Warning>
  `tonumber(int64)` collapses back to a double and **loses precision above 2^53**. Keep large addresses in `uintptr_t`/`int64_t` cdata and only convert at the very end.
</Warning>

### Calling conventions

In a function pointer type you can specify `__cdecl`, `__stdcall`, `__fastcall`, or `__thiscall`. On **x64 they're all ignored** (there's a single ABI); they only matter for 32-bit targets.

### Memory, copying, and introspection

<Tabs items={["allocate", "copy & fill", "introspect", "type checks"]}>
  <Tab title="allocate">
    ```lua
    -- "?" is a runtime length; the third arg initializes the array.
    local n = 4
    local buf = ffi.new("unsigned char[?]", n, {10, 20, 30, 40})
    print(buf[0], buf[n - 1]) -- 10, 40
    ```
  </Tab>

  <Tab title="copy & fill">
    ```lua
    local source = ffi.new("uint8_t[3]", {10, 0, 20})
    local destination = ffi.new("char[16]")
    ffi.fill(destination, ffi.sizeof(destination), 0)
    ffi.copy(destination, source, ffi.sizeof(source))
    local bytes = ffi.string(destination, 3) -- Keeps the embedded zero byte.
    ffi.copy(destination, "hello") -- Also copies the terminating zero byte.
    print(#bytes, ffi.string(destination)) -- 3, "hello"
    ```
  </Tab>

  <Tab title="introspect">
    ```lua
    local Pair = ffi.typeof("struct { int a, b; }")
    print(ffi.sizeof(Pair))        -- 8 bytes on Windows x64.
    print(ffi.offsetof(Pair, "b")) -- 4-byte field offset.
    print(ffi.alignof(Pair))       -- 4-byte alignment.
    ```
  </Tab>

  <Tab title="type checks">
    ```lua
    local value = ffi.new("int", 42)
    print(ffi.istype("int", value)) -- true
    print(ffi.typeof(value))        -- The ctype of this value.
    local e = ffi.errno()           -- C runtime errno, not Win32 GetLastError.
    ```
  </Tab>
</Tabs>

### Platform introspection

Branch on architecture instead of hardcoding - offsets and signatures differ between x86 and x64:

```lua
print(ffi.os)           -- "Windows" for CS2.
print(ffi.arch)         -- "x64" for CS2.
print(ffi.abi("64bit")) -- true; other queries include "le", "win", and "gc64".
```

### `ffi.gc` - finalizers

Attach a finalizer that runs when its cdata is garbage-collected. This example uses a Lua-owned array and a bookkeeping callback:

```lua
local buffer = ffi.gc(ffi.new("uint8_t[16]"), function()
  print("Buffer collected")
end)
buffer[0] = 42
print(buffer[0])

-- Remove the callback when ownership or cleanup policy changes.
ffi.gc(buffer, nil)
```

For a native resource, the finalizer must call its documented release function exactly once. Garbage collection timing is unspecified; release scarce resources explicitly when their work is finished.

### `ffi.metatype` - methods and operators on cdata

Attach a metatable to a C type and its values become first-class Lua objects: indexable, callable, comparable, with a custom constructor via `__new`.

```lua
local ffi = require("ffi")
ffi.cdef[[ typedef struct { uintptr_t v; } addr_t; ]]

local addr
addr = ffi.metatype("addr_t", {
  __new      = function(ct, p) return ffi.new(ct, ffi.cast("uintptr_t", p)) end,
  __lt       = function(a, b) return a.v < b.v end,           -- enables <  and >
  __tostring = function(self) return ("addr<0x%x>"):format(tonumber(self.v)) end,
  __index    = {
    to_int = function(self)      return tonumber(self.v) end,
    at     = function(self, off) return addr(self.v + off) end,
  },
})

local p = addr(0x1000)
print(p:at(0x10))    -- addr<0x1010>
print(addr(1) < addr(2))   -- true
```

<Note>
  A single metatable can mix a **table** `__index` with **function** metamethods. Calling `addr(x)` dispatches to `__new`. Forward-declare `addr` so the `at` closure captures the local constructor. The small numeric addresses above are values only; the example never dereferences them. Its `tonumber` conversions are suitable only for values exactly representable as Lua numbers.
</Note>

### Metatypes: more metamethods

Beyond `__index` / `__new`, a metatype accepts the full arithmetic and comparison set - `__add`, `__sub`, `__eq`, `__len`, `__concat`, `__call` - plus `__gc`, a finalizer that runs for **every** instance of that type (an alternative to per-object `ffi.gc`):

```lua
local Record = ffi.metatype("struct { int id; }", {
  __gc = function(self) print("Collected record", self.id) end,
  __eq = function(a, b) return a.id == b.id end,
})
local first, second = Record(7), Record(7)
print(first == second) -- true
```

### `ffi.typeof` templates with `$`

`$` is a placeholder in a C declaration, substituted by a ctype **or a number** argument. This is how you build pointer/array/struct types programmatically without string concatenation:

```lua
local Pair = ffi.typeof("struct { int a, b; }")

local PairPtr = ffi.typeof("$*",   Pair)   -- pointer to Pair
local PairVLA = ffi.typeof("$[?]", Pair)   -- variable-length array of Pair

local n = 8
local Fixed = ffi.typeof("int[$]", n)      -- int[8] - length from a Lua number

-- Nesting structs by reference (great for big Win32 / PE headers):
local Header = ffi.typeof("struct { $ dir[16]; }", PairPtr)
```

<Tip>
  **Cache ctypes** - parsing declaration strings repeatedly adds work and can create distinct anonymous types. Build each type once outside hot callbacks and reuse its constructor. Use `pcall(ffi.typeof, ...)` when probing whether a named type already exists.
</Tip>

### Callbacks - Lua functions as C function pointers

`ffi.cast` can turn a Lua function into a C function pointer. This example owns the callback and invokes it directly, so no native system retains it:

```lua
local cb = ffi.cast("int(*)(int)", function(value)
  return value * 2
end)

print(cb(21)) -- 42
cb:set(function(value) return value * 3 end)
print(cb(21)) -- 63
cb:free() -- No code may call this pointer after it is freed.
```

<Warning>
  Callback slots are limited and must be released explicitly with `cb:free()`. Retain the callback handle so you can release or replace it. Before freeing a callback registered with native code, unregister it and ensure no call is still in progress. C-to-Lua callbacks also have JIT restrictions; consult the FFI reference before using them in a compiled loop.
</Warning>

### Reusable runtime ctypes

Named C structures cannot be redefined. When you need a private layout, create an anonymous ctype once and reuse it:

```lua
local Record = ffi.typeof("struct { int value; }")
local first = Record(10)
local second = Record(20)
print(first.value + second.value) -- 30
```

### Pitfall: cdata lifetime

`ffi.cast` and pointer arithmetic **do not keep the source allocation alive**. If nothing else references it, the GC frees it and your pointer dangles:

```lua
-- BUG: the array may be collected while `p` still points into it.
local p = ffi.cast("int*", ffi.new("int[10]"))

-- FIX: keep the owner alive for as long as the pointer is used.
local arr = ffi.new("int[10]")
local p   = ffi.cast("int*", arr)   -- `arr` anchors the memory
```

## Further reading

<Columns cols={2}>
  <Card title="Lua Crash Course" icon="graduation-cap" href="/cs2/api_reference/tutorials/lua-crash-course">
    New to Lua? Start with the language essentials before diving into FFI.
  </Card>

  <Card title="Advanced LuaJIT" icon="wand-sparkles" href="/cs2/api_reference/tutorials/advanced-luajit">
    Non-obvious LuaJIT 2.1 language tricks beyond FFI.
  </Card>

  <Card title="API Reference" icon="code" href="/cs2/api_reference/introduction/overview">
    Explore the full Lua API: entity, render, trace, ui, utils, and more.
  </Card>

  <Card title="Win32 API on MSDN" icon="external-link" href="https://learn.microsoft.com/en-us/windows/win32/api/" arrow>
    Official Microsoft reference for every WinAPI function - verify signatures before declaring them with `ffi.cdef`.
  </Card>

  <Card title="LuaJIT FFI docs" icon="book-open" href="https://luajit.org/ext_ffi.html" arrow>
    The complete FFI reference: `ffi.cdef`, `ffi.cast`, `ffi.new`, `ffi.string`, and more.
  </Card>
</Columns>

<Note>
  This guide is adapted from the community FFI crash course originally written by **owen** and **sapphyrus**, and expanded & improved by **Salvatore**. FFI is powerful but unforgiving - incorrect casts or addresses crash the game, so test incrementally.
</Note>
