> 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, calling conventions, and casting - for CS:GO Lua developers.
icon: cpu
---

# FFI Crash Course

An in-depth tour of FFI for anyone, regardless of experience, who wants to interact directly with the game's memory from Lua. This guide covers the fundamentals, plus tips and tricks to make you a more competent Lua developer.

<Info>
  The first section uses **pseudo-C** snippets. C has dedicated operators for the low-level operations that matter to us, and it's the language FFI exposes - so understanding how it works is essential. Each concept is shown in C first, then translated to its Lua equivalent.
</Info>

<Warning>
  **CS:GO runs on the 32-bit Source engine (x86).** Two things follow from this that do **not** apply to 64-bit games like CS2:

  * **Pointers are 4 bytes** (not 8).
  * **Calling conventions are significant.** `__cdecl`, `__stdcall`, `__fastcall`, and `__thiscall` are distinct ABIs on x86, and you must declare the right one or the call corrupts the stack and crashes the game. On x64 there's a single convention and these are all ignored - here they are not.

  Keep this in mind throughout; the practical sections lean on it heavily.
</Warning>

## 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.

## 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 doesn't always point to a valid variable. Pointers that point to nothing are called **null pointers**. This splits pointers into two kinds: **safe** and **unsafe**. Safe pointers are easier to reason about, but with FFI you'll mostly deal with unsafe ones - so understanding safe pointers first makes the rest click.

<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` now holds the address of `floating_point`. It's *safe* because that variable is guaranteed to have an address, and the pointer is guaranteed to point at it.
  </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>
  The unsafe example above will **crash** the application if run - `0x1234` is almost certainly not a valid address. Note that the `&` operator is never used for unsafe pointers; it's only for creating safe pointers in C.
</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?

With FFI we only have access to *memory*, not the high-level source abstraction that would let us create safe pointers. Unsafe pointers are simply a way of telling our code **how to interpret a memory address**. The "variables" they point to can be anything: functions, engine-defined structures, custom user types, or basic integral types. The Neverlose Lua API gives us helpers like [`utils.opcode_scan`](/csgo/api-reference/namespaces/utils) and [`utils.create_interface`](/csgo/api-reference/namespaces/utils) to scan memory and retrieve important Source engine structures - covered later.

## 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 `0x10405060` 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*)0x10405060;
int first_4_bytes = *int_pointer;

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

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; // An array name IS a pointer to its first element.
int our_2nd_value = *(our_array + 1);
```

<Note>
  Integers in C are 4 bytes. If `our_array` lives at `0x10001000`, then `our_array + 1` is **not** `0x10001001` - it's `0x10001004`, because the size of the type (4 bytes) is taken into account.
</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

To use FFI you must include the library with `require`:

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

FFI is then available as `ffi.*` throughout your script.

<Tip>
  The full LuaJIT FFI surface - including `ffi.C` - is available. Refer to the official LuaJIT FFI documentation for everything you can do.
</Tip>

### Dereferencing in Lua

Lua has no dereference operator like C's `*`. But we can treat a pointer like an array of one element - because in memory an array *is* just a pointer to its first element. To read the first element, use `[0]`:

```lua
-- These are equivalent:
-- *our_array        (C: dereference, gives the first value)
-- our_array[0]      (Lua: add 0 to the pointer, then dereference)
local first_value = our_array[0]
```

A pointer is, in memory, identical to an array containing one value - both hold an address pointing to a single value. So in Lua we use `[0]` to dereference.

### Signatures and signature scanning

Signatures are sequences of bytes in memory. Neverlose exposes a signature scanner through [`utils.opcode_scan(module, signature[, offset])`](/csgo/api-reference/namespaces/utils), which returns a `userdata` pointer to the first match. The pattern is **space-separated hex bytes** in IDA style, and `?` marks a **wildcard** byte that can be any value:

```lua
-- Pattern format: space-separated hex, "?" = wildcard byte.
"55 8B EC 83 E4 F8 83 EC ? 56 8B 75 08"
```

Wildcards matter because some bytes (relative offsets, addresses patched at load time) change between builds, while the surrounding opcodes stay stable. A scan walks the module's memory comparing against the pattern until it matches completely, then returns the address of the first match. Make sure your signature is unique - or that all matches are identical.

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

-- Scan client.dll and always handle the not-found case - good practice.
local address = utils.opcode_scan("client.dll", "55 8B EC 83 E4 F8 83 EC ? 56 8B 75 08")
  or error("Signature was not found")

-- CS:GO is 32-bit. A free (non-member) function commonly uses __cdecl - declare
-- the calling convention explicitly so the cast matches the target's ABI.
local some_function = ffi.cast("void(__cdecl*)(void*, float*)", address)

-- You can now call some_function with the correct arguments.
```

<Tip>
  The optional third `offset` argument is added to the resolved address before it's returned - handy when your signature lands a few bytes before the data you actually want (e.g. a relative call you need to resolve).
</Tip>

<Tip>
  Sig'ing a function instead of relying on a fixed virtual-function index protects you from updates: indices into frequently-changing classes shift around, but a good byte signature keeps resolving to the right function.
</Tip>

### Calling conventions on x86

This is the part that has no equivalent on 64-bit titles. On x86 the convention decides **where arguments live and who cleans up the stack**:

| Convention   | `this` / args                                   | Typical use in Source                                        |
| ------------ | ----------------------------------------------- | ------------------------------------------------------------ |
| `__cdecl`    | All args on the stack; caller cleans up.        | Free C-style functions.                                      |
| `__stdcall`  | All args on the stack; callee cleans up.        | The entire Windows API.                                      |
| `__thiscall` | `this` in **ECX**, remaining args on the stack. | C++ **member functions** - including every virtual function. |
| `__fastcall` | First two args in ECX/EDX, rest on the stack.   | Some hand-optimized engine routines.                         |

<Warning>
  Pick the wrong one and the stack ends up misaligned - the call returns into garbage and the game crashes. When you're calling a class method (anything with a `this`), it's almost always `__thiscall`.
</Warning>

### The interface system

Source is made of many DLLs that must talk to each other. Each module exports interfaces through a `CreateInterface` function, keyed by a version string, and [`utils.create_interface(module, interface)`](/csgo/api-reference/namespaces/utils) returns a `userdata` pointer to the requested interface - a class containing all its functions. Interface version strings look like `VClient018` (client.dll) or `VEngineClient014` (engine.dll).

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

-- Grab the client interface exported by client.dll.
local client_interface = ffi.cast("void***", utils.create_interface("client.dll", "VClient018"))
  or error("interface not found")

-- Virtual functions live in an array of pointers (the virtual function table / VFT)
-- held in the first member of every interface. Dereference once to reach it.
local vtable = client_interface[0]

-- Say index 5 is a member function of type void(this, int) that we want to call.
-- On x86 the `this` pointer rides in ECX, so the type MUST be __thiscall.
ffi.cast("void(__thiscall*)(void*, int)", vtable[5])(client_interface, 10)
```

<Info>
  The interface pointer returned by `utils.create_interface` is the `this` pointer for its virtual functions - always pass it back as the first argument when calling them.
</Info>

<Tip>
  Resolving the vtable and getting the `__thiscall` cast right by hand is fiddly. Neverlose provides [`utils.get_vfunc`](/csgo/api-reference/namespaces/utils), which wraps a vtable slot into a ready-to-call function from a module + interface + index + FFI type - the convenience path for calling virtual functions:

  ```lua
  -- index 5 of the client interface, typed as void(__thiscall*)(void*, int)
  local fn = utils.get_vfunc("client.dll", "VClient018", 5, "void(__thiscall*)(void*, int)")
  ```

  See the [`utils.get_vfunc`](/csgo/api-reference/namespaces/utils) reference for the exact calling form.
</Tip>

### Casting

Casting via `ffi.cast` tells Lua how to interpret a value - just like the C casts shown earlier. A `userdata` pointer returned from [`utils.opcode_scan`](/csgo/api-reference/namespaces/utils) or [`utils.create_interface`](/csgo/api-reference/namespaces/utils) can be cast into a typed pointer, letting you read memory and call functions freely.

<AccordionGroup>
  <Accordion title="Worked example: calling a virtual function from an interface" icon="code" defaultOpen>
    ```lua
    local ffi = require("ffi")

    -- Resolve the interface exported by client.dll.
    local client_interface = ffi.cast("void***", utils.create_interface("client.dll", "VClient018"))
      or error("interface is nil")

    -- Dereference once to get the VFT (points to the first entry).
    local vtable = client_interface[0]

    -- Index 8 is the function we need; it returns an int.
    -- Member functions are __thiscall on x86 - the `this` pointer goes in ECX.
    local get_value = ffi.cast(ffi.typeof("int(__thiscall*)(void*)"), vtable[8])

    -- Virtual functions take the `this` pointer (the interface) as their first argument.
    local value = get_value(client_interface)
    print("resolved value:", value)
    ```
  </Accordion>
</AccordionGroup>

## Calling WinAPI with ffi.C

`ffi.C` is the **default C library namespace** - it exposes every symbol already loaded into the process, including the entire Windows API (`kernel32.dll`, `user32.dll`, ...). You don't need a signature for these: just declare the function's signature with `ffi.cdef`, then call it as `ffi.C.FunctionName(...)`.

<Warning>
  On 32-bit Windows, **the WinAPI is `__stdcall`**. Declare your prototypes with `__stdcall` so the names resolve and the stack is cleaned up by the callee - a plain `__cdecl` declaration of a `__stdcall` function will crash on x86.
</Warning>

<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, return type, and the `__stdcall` convention.

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

    ffi.cdef[[
        int __stdcall GetAsyncKeyState(int vKey);
        unsigned long __stdcall GetTickCount(void);
    ]]
    ```
  </Step>

  <Step title="Call it through ffi.C" icon="terminal">
    The declared names are now available on `ffi.C`.

    ```lua
    -- VK_LBUTTON = 0x01. The high bit is set while the key is down.
    if bit.band(ffi.C.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. If your declared signature doesn't match the real WinAPI function (wrong argument count, wrong types, wrong return type, wrong convention), the call corrupts the stack and crashes the game. Always verify against the official MSDN signature.
</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
    ffi.cdef[[
        int __stdcall MessageBoxA(void* hWnd, const char* text, const char* caption, unsigned int type);
    ]]

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

  <Tab title="Wide variant">
    ```lua
    ffi.cdef[[
        int __stdcall MultiByteToWideChar(unsigned int cp, unsigned long flags,
            const char* str, int cb, wchar_t* wide, int cch);
        int __stdcall 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)
      local buf = ffi.new("wchar_t[?]", len)
      ffi.C.MultiByteToWideChar(65001, 0, s, -1, buf, len)
      return buf
    end

    ffi.C.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 __stdcall QueryPerformanceCounter(int64_t* lpPerformanceCount);
]]

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

<Note>
  For pure timing or scheduling you usually don't need WinAPI at all - Neverlose already provides helpers like [`utils.execute_after`](/csgo/api-reference/namespaces/utils) and the [`globals`](/csgo/api-reference/namespaces/globals) namespace. Reach for `ffi.C` when you need something the Lua API doesn't expose.
</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 { FL_ONGROUND = 1, FL_DUCKING = 2, FL_FROZEN = 4 }; ]]

    -- Enum constants are available on ffi.C:
    if bit.band(flags, ffi.C.FL_ONGROUND) ~= 0 then end
    ```
  </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 __cdecl 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 handles, masks, and timestamps:

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

<Warning>
  `tonumber(int64)` collapses back to a double and **loses precision above 2^53**. Keep large values in `uintptr_t`/`int64_t` cdata and only convert at the very end. Note that on x86 a raw **pointer** is only 4 bytes (`uintptr_t` is 32-bit), so addresses themselves fit in a regular number - but 64-bit handles and Steam IDs still need the cdata path.
</Warning>

### Calling conventions

In a function pointer type you can specify `__cdecl`, `__stdcall`, `__fastcall`, or `__thiscall`. On **x86 (CS:GO) these are all distinct and significant** - choosing the wrong one misaligns the stack and crashes. (On x64 there's a single ABI, so they're ignored - the opposite of what you have here.) See [Calling conventions on x86](#calling-conventions-on-x86) above for the breakdown.

### 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 buf = ffi.new("unsigned char[?]", n, data)
    ```
  </Tab>

  <Tab title="copy & fill">
    ```lua
    ffi.fill(ptr, len, 0)        -- memset(ptr, 0, len)
    ffi.copy(dst, src, len)      -- memcpy
    ffi.copy(dst, "hello")       -- copies the string PLUS a trailing \0 (#s + 1 bytes)
    local s = ffi.string(ptr, len)   -- raw bytes -> Lua string
    ```
  </Tab>

  <Tab title="introspect">
    ```lua
    ffi.sizeof(Header)           -- byte size of a type/value
    ffi.offsetof(Header, "dir")  -- field offset within a struct
    ffi.alignof(Pair)            -- alignment requirement
    ```
  </Tab>

  <Tab title="type checks">
    ```lua
    ffi.istype("int", x)         -- true if x is that ctype
    ffi.typeof(value)            -- the ctype of a cdata value
    local e = ffi.errno()        -- read C errno after a failing call (or set it)
    ```
  </Tab>
</Tabs>

### Platform introspection

Branch on architecture instead of hardcoding - offsets and signatures differ between x86 and x64, and CS:GO reports **x86**:

```lua
ffi.os            -- "Windows"
ffi.arch          -- "x86"   (CS:GO is 32-bit)
ffi.abi("32bit")  -- true on CS:GO; also "le", "win", "fpu", "hardfp", ...
```

### `ffi.gc` - finalizers for raw pointers

Attach a destructor that runs when the cdata is garbage-collected - automatic cleanup for manually allocated memory or OS handles:

```lua
ffi.cdef[[
  void* __stdcall VirtualAlloc(void*, size_t, uint32_t, uint32_t);
  int   __stdcall VirtualFree(void*, size_t, uint32_t);
]]

-- MEM_COMMIT | MEM_RESERVE = 0x3000, PAGE_EXECUTE_READWRITE = 0x40
local mem = ffi.gc(ffi.C.VirtualAlloc(nil, size, 0x3000, 0x40), function(p)
  ffi.C.VirtualFree(p, 0, 0x8000)  -- MEM_RELEASE; runs automatically on GC
end)
```

### `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 = 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` (the methods) with **function** metamethods (`__lt`, `__new`, `__tostring`). Calling the metatype like a function (`addr(x)`) dispatches to `__new`. This is the idiomatic way to wrap raw addresses in a typed, operator-friendly object.
</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 Handle = ffi.metatype("struct { void* h; }", {
  __gc  = function(self) ffi.C.CloseHandle(self.h) end,  -- auto-cleanup per type
  __eq  = function(a, b) return a.h == b.h end,
})
```

### `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** - `ffi.typeof` parses C on every call. Building a type once and reusing it can be *thousands* of times faster in hot paths (think \~2 ms vs \~3000 ms over 10M calls). Pair it with `pcall(ffi.typeof, ...)` when the declaration might be invalid.
</Tip>

### Callbacks - Lua functions as C function pointers

You can hand a **Lua function to C** where it expects a function pointer - LuaJIT builds the trampoline automatically. This is how you service WinAPI callbacks (`EnumWindows`, `SetWindowsHookEx`, a `qsort` comparator, ...). On x86, **match the callback's convention** - Win32 callbacks are usually `__stdcall`:

```lua
ffi.cdef[[
  typedef int (__stdcall *WNDENUMPROC)(void*, intptr_t);
  int __stdcall EnumWindows(WNDENUMPROC, intptr_t);
]]

local cb = ffi.cast("WNDENUMPROC", function(hwnd, lparam)
  -- inspect each window...
  return 1   -- return 1 to keep enumerating
end)

ffi.C.EnumWindows(cb, 0)
cb:free()    -- release the callback slot when you're done
```

<Warning>
  Callbacks have sharp edges: the number of **active** callbacks is limited (\~1000), C->Lua calls are **not** JIT-compiled (slower than normal calls), and if you drop the Lua reference to `cb` the GC frees it and the C side calls into freed memory. Keep the handle alive, call `cb:free()` when finished, or reuse a slot with `cb:set(new_fn)`.
</Warning>

### Unique names for runtime cdefs

A C type **cannot be redefined** - a second `ffi.cdef` of the same name throws. When you must declare types at runtime, generate a unique name with a counter or timestamp suffix:

```lua
local name = "Tmp" .. unique_suffix          -- e.g. a counter or timestamp
ffi.cdef(("typedef struct {} %s;"):format(name))
local T = ffi.typeof(name)
```

### 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="/csgo/guides/lua-crash-course">
    New to Lua? Start with the language essentials before diving into FFI.
  </Card>

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

  <Card title="API Reference" icon="code" href="/csgo/api-reference/namespaces/_g">
    Explore the full Lua API: entity, render, esp, 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, conventions, or addresses crash the game, so test incrementally.
</Note>
