0Pricing
Lua Academy · Lesson

Callbacks: Passing Lua Functions to C

Use ffi.cast to create C callbacks that call back into Lua code.

What Are C Callbacks?

Some C APIs require you to pass a function pointer that the C code will call back. The FFI's ffi.cast lets you create C-compatible function pointers from Lua functions.

Declaring a Callback Type

First declare the function pointer type in cdef.

local ffi = require("ffi")
ffi.cdef[[
  typedef void (*callback_t)(int event, void *data);
  void register_handler(callback_t cb);
]]

All lessons in this course

  1. FFI Basics: ffi.cdef and ffi.load
  2. Calling C Functions via FFI
  3. Pointers, Structs, and Arrays in FFI
  4. Callbacks: Passing Lua Functions to C
← Back to Lua Academy