FFI and native extensions
suggest changeSometimes PHP code needs to call native code: a C library with no PHP binding, an operating system API, or a hot loop rewritten in C. PHP gives you two ways to do it:
- FFI (Foreign Function Interface, the
ffiextension, PHP 7.4+): declare C functions and types in a string and call them from PHP. Nothing to compile on the PHP side. - A native extension: a shared library written in C against the Zend API, loaded with
extension=...inphp.ini. That's howmbstring,pdoorredisare built.
This article covers FFI in depth, then shows a minimal native extension and how to choose between the two. If you want application-level plugins written in PHP, see Plugins and extensions. For building existing extensions from source, see Compile PHP Extensions.
Enabling FFI
FFI ships with PHP but must be enabled when PHP is built (--with-ffi) or loaded in php.ini:
extension=ffi
; "preload" (the default): FFI works in the CLI and in preloaded code only
; "true": FFI works everywhere, including web requests
; "false": FFI is disabled
ffi.enable=preload
Check it with php -m | grep FFI or extension_loaded('ffi'). On Debian and Ubuntu it's part of the php8.x-common package; on Windows php_ffi.dll is in the ext directory of the official build.
The default ffi.enable=preload is a security measure. FFI can read and write any memory in the process, so it shouldn't be usable from arbitrary code in a web request. In the CLI it just works. Under PHP-FPM or CGI only code loaded during OPcache preloading (see below) may use it:
<?php
try {
$libc = FFI::cdef('int abs(int n);', 'ucrtbase.dll');
echo $libc->abs(-1), "\n";
} catch (FFI\Exception $e) {
echo get_class($e), ": ", $e->getMessage(), "\n";
}
Running it with php-cgi and the default setting:
FFI\Exception: FFI API is restricted by "ffi.enable" configuration directive
Calling a function from the C library
FFI::cdef($declarations, $library) parses C declarations and loads the shared library. The returned FFI object exposes the declared functions as methods:
<?php
$libc = FFI::cdef(<<<'C'
size_t strlen(const char *s);
int abs(int n);
double sqrt(double x);
C, PHP_OS_FAMILY === 'Windows' ? 'ucrtbase.dll' : 'libc.so.6');
var_dump($libc->strlen("hello, FFI"));
var_dump($libc->abs(-42));
var_dump($libc->sqrt(2.0));
Output:
int(10)
int(42)
float(1.4142135623730951)
Things to know:
- The declarations are plain C, but without the preprocessor: no
#include, no macros. You copy the prototypes and types you need from the library's header files. - The library name is passed to
dlopen()(LoadLibrary()on Windows), so the usual search rules apply. A name likelibc.so.6is looked up on the system library path; a path such as./geom.dllis relative to the current working directory, not the script. Use__DIR__ . '/geom.dll'to be safe. - Scalars convert automatically: PHP
intto C integer types,floattofloat/double,booltobool, and a PHPstringcan be passed where C expectsconst char *.
The same works for operating system APIs. On Windows, kernel32.dll functions are available directly:
<?php
$k32 = FFI::cdef(<<<'C'
typedef unsigned long DWORD;
DWORD GetCurrentProcessId(void);
unsigned long long GetTickCount64(void);
DWORD GetEnvironmentVariableA(const char *name, char *buf, DWORD size);
C, 'kernel32.dll');
var_dump($k32->GetCurrentProcessId() === getmypid());
printf("uptime: %.1f hours\n", $k32->GetTickCount64() / 3_600_000);
$buf = $k32->new('char[260]');
$len = $k32->GetEnvironmentVariableA('OS', $buf, FFI::sizeof($buf));
echo "OS=", FFI::string($buf, $len), "\n";
Output:
bool(true)
uptime: 88.4 hours
OS=Windows_NT
Windows headers use typedefs like DWORD, so you declare them yourself before using them.
Building your own library
FFI is most useful with a library you control. Here's a small C library with structs, pointers, arrays, callbacks and strings. We'll call it from PHP in the next sections.
geom.c:
#include <ctype.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef _WIN32
#define EXPORT __declspec(dllexport)
#else
#define EXPORT __attribute__((visibility("default")))
#endif
typedef struct {
double x;
double y;
} Point;
typedef int (*visit_fn)(int index, double value);
EXPORT double distance(Point a, Point b) {
double dx = a.x - b.x, dy = a.y - b.y;
return sqrt(dx * dx + dy * dy);
}
EXPORT void translate(Point *p, double dx, double dy) {
p->x += dx;
p->y += dy;
}
EXPORT double sum(const double *values, size_t count) {
double total = 0;
for (size_t i = 0; i < count; i++) total += values[i];
return total;
}
/* calls fn for each value, stops early when fn returns non-zero */
EXPORT int for_each(const double *values, size_t count, visit_fn fn) {
for (size_t i = 0; i < count; i++) {
if (fn((int)i, values[i]) != 0) return (int)i;
}
return -1;
}
/* writes at most dst_size-1 chars + '\0', returns number of chars written */
EXPORT size_t to_upper(const char *src, char *dst, size_t dst_size) {
size_t i = 0;
for (; src[i] && i + 1 < dst_size; i++) dst[i] = (char)toupper((unsigned char)src[i]);
dst[i] = '\0';
return i;
}
/* returns a malloc'ed string; the caller must release it with free_string() */
EXPORT char *greet(const char *name) {
size_t n = strlen(name) + 16;
char *s = malloc(n);
snprintf(s, n, "Hello, %s!", name);
return s;
}
EXPORT void free_string(char *s) {
free(s);
}
Compile it into a shared library:
# Windows (clang from the Visual Studio LLVM tools, or clang-cl / cl)
clang -O2 -shared -o geom.dll geom.c
# Linux
clang -O2 -shared -fPIC -o libgeom.so geom.c -lm
# macOS
clang -O2 -shared -o libgeom.dylib geom.c
The library must match PHP's architecture: a 64-bit PHP can't load a 32-bit DLL.
Structs and pointers
$ffi->new('Point') allocates a C struct that PHP owns. Fields are read and written like object properties. FFI::addr() takes its address so C can modify it in place:
<?php
$ffi = FFI::cdef(<<<'C'
typedef struct { double x; double y; } Point;
double distance(Point a, Point b);
void translate(Point *p, double dx, double dy);
C, __DIR__ . '/geom.dll');
// structs: allocate, fill, pass by value
$a = $ffi->new('Point');
$a->x = 0;
$a->y = 0;
$b = $ffi->new('Point');
$b->x = 3;
$b->y = 4;
echo $ffi->distance($a, $b), "\n";
// pass a pointer so C can modify the struct
$ffi->translate(FFI::addr($b), 10, -1);
printf("b = (%.1f, %.1f)\n", $b->x, $b->y);
var_dump($b);
echo FFI::sizeof($b), " bytes\n";
Output:
5
b = (13.0, 3.0)
object(FFI\CData:struct <anonymous>)#3 (2) {
["x"]=>
float(13)
["y"]=>
float(3)
}
16 bytes
Every C value lives in an FFI\CData object. Use the instance methods $ffi->new(), $ffi->cast() and $ffi->type(): they know the types you declared (like Point). Calling FFI::new(), FFI::cast() or FFI::type() statically is deprecated since PHP 8.3. FFI::addr(), FFI::sizeof(), FFI::string(), FFI::memcpy() and FFI::free() are still static.
Arrays, buffers and strings
<?php
$ffi = FFI::cdef(<<<'C'
double sum(const double *values, size_t count);
size_t to_upper(const char *src, char *dst, size_t dst_size);
char *greet(const char *name);
void free_string(char *s);
C, __DIR__ . '/geom.dll');
// a C array of 5 doubles, zero-initialized
$values = [1.5, 2.5, 3.0, 4.0, 5.0];
$arr = $ffi->new('double[' . count($values) . ']');
foreach ($values as $i => $v) {
$arr[$i] = $v;
}
echo "count: ", count($arr), ", sizeof: ", FFI::sizeof($arr), "\n";
echo "sum: ", $ffi->sum($arr, count($arr)), "\n";
// output buffer: C writes into memory we own
$buf = $ffi->new('char[16]');
$n = $ffi->to_upper("hello ffi world, this is long", $buf, FFI::sizeof($buf));
var_dump($n, FFI::string($buf), FFI::string($buf, 5));
// memory allocated by C must be freed by C
$p = $ffi->greet("PHP");
var_dump($p);
echo FFI::string($p), "\n";
$ffi->free_string($p);
Output:
count: 5, sizeof: 40
sum: 16
int(15)
string(15) "HELLO FFI WORLD"
string(5) "HELLO"
object(FFI\CData:char*)#4 (1) {
[0]=>
string(1) "H"
}
Hello, PHP!
- A C array passed to a function expecting a pointer decays to a pointer, just like in C.
count()works on C arrays, and you canforeachover them. Indexing past the end throwsFFI\Exception: C array index out of bounds. - A returned
char *is aCDatapointer, not a PHP string.FFI::string($ptr)copies a zero-terminated string into PHP;FFI::string($ptr, $len)copies exactly$lenbytes, which also works for binary data. - Whoever allocates memory frees it. Memory returned by C's
malloc()must go back to the library'sfree(), which is why good C APIs export a function likefree_string(). - A
NULLpointer returned from C becomes PHPnull. ForCDatapointers you got some other way, useFFI::isNull($ptr).
Memory ownership
By default $ffi->new() returns memory owned by PHP: it's freed automatically when the last reference to the CData goes away. Pass false as the second argument to get unmanaged memory, which you must release with FFI::free(), exactly like malloc()/free():
<?php
$ffi = FFI::cdef(); // no library: just the C type system
$before = memory_get_usage();
$owned = $ffi->new('char[1000000]'); // owned by PHP
echo "owned: +", memory_get_usage() - $before, " bytes\n";
unset($owned); // freed automatically
echo "unset: +", memory_get_usage() - $before, " bytes\n";
$raw = $ffi->new('char[1000000]', false); // unmanaged, like malloc()
echo "manual: +", memory_get_usage() - $before, " bytes\n";
FFI::free($raw); // you must free it yourself
echo "freed: +", memory_get_usage() - $before, " bytes\n";
Output:
owned: +1003744 bytes
unset: +32 bytes
manual: +1003744 bytes
freed: +256 bytes
Use unmanaged memory when C keeps a pointer after the call returns (for example a library that stores a buffer in a context struct). If you pass owned memory there, PHP frees it when your variable goes out of scope and the library ends up with a dangling pointer. A third argument true allocates persistent memory that survives across requests.
Callbacks
A PHP closure can be passed where C expects a function pointer. FFI generates a native trampoline that calls back into PHP:
<?php
$ffi = FFI::cdef(<<<'C'
typedef int (*visit_fn)(int index, double value);
int for_each(const double *values, size_t count, visit_fn fn);
C, __DIR__ . '/geom.dll');
$values = [3.0, 8.5, 1.25, 42.0, 7.0];
$arr = $ffi->new('double[5]');
foreach ($values as $i => $v) $arr[$i] = $v;
$stoppedAt = $ffi->for_each($arr, 5, function (int $i, float $v): int {
echo "visit $i: $v\n";
return $v > 40 ? 1 : 0; // non-zero stops the loop
});
echo "stopped at index $stoppedAt\n";
Output:
visit 0: 3
visit 1: 8.5
visit 2: 1.25
visit 3: 42
stopped at index 3
Callbacks that receive void * need a cast to the real type. Here the C library's own qsort() sorts a C array with a PHP comparison function:
<?php
$libc = FFI::cdef(<<<'C'
typedef int (*compare_fn)(const void *a, const void *b);
void qsort(void *base, size_t count, size_t size, compare_fn cmp);
C, PHP_OS_FAMILY === 'Windows' ? 'ucrtbase.dll' : 'libc.so.6');
$nums = [42, 7, 19, 3, 25];
$arr = $libc->new('int[' . count($nums) . ']');
foreach ($nums as $i => $n) $arr[$i] = $n;
$calls = 0;
$libc->qsort($arr, count($arr), FFI::sizeof($arr[0]), function ($a, $b) use ($libc, &$calls) {
$calls++;
// a and b are void*: cast them to int* to read the values
$x = $libc->cast('int *', $a)[0];
$y = $libc->cast('int *', $b)[0];
return $x <=> $y;
});
$sorted = [];
foreach ($arr as $v) $sorted[] = $v;
echo implode(', ', $sorted), " ($calls comparisons)\n";
Output:
3, 7, 19, 25, 42 (10 comparisons)
Two caveats: an exception can't unwind through C frames. If the closure throws, PHP stops with Fatal error: Throwing from FFI callbacks is not allowed, and a try/catch around the FFI call doesn't help. Catch everything inside the closure and return an error code instead. And the trampoline is only valid while the closure is alive, so don't let C store a callback beyond the call unless you keep a reference to the closure.
Errors
Mistakes in declarations and calls throw FFI\Exception (or its subclass FFI\ParserException for invalid C):
<?php
$ffi = FFI::cdef('char *greet(const char *name);', __DIR__ . '/geom.dll');
try {
$ffi->nope();
} catch (FFI\Exception $e) {
echo get_class($e), ": ", $e->getMessage(), "\n";
}
try {
FFI::cdef('int broken(;');
} catch (FFI\ParserException $e) {
echo get_class($e), ": ", $e->getMessage(), "\n";
}
try {
FFI::cdef('int f(void);', 'no-such-lib.dll');
} catch (FFI\Exception $e) {
echo get_class($e), ": ", $e->getMessage(), "\n";
}
try {
FFI::cdef('int no_such_function(void);', __DIR__ . '/geom.dll');
} catch (FFI\Exception $e) {
echo get_class($e), ": ", $e->getMessage(), "\n";
}
$arr = $ffi->new('int[3]');
try {
$arr[5] = 1;
} catch (FFI\Exception $e) {
echo get_class($e), ": ", $e->getMessage(), "\n";
}
Output:
FFI\Exception: Attempt to call undefined C function 'nope'
FFI\ParserException: ')' expected, got ';' at line 1
FFI\Exception: Failed loading 'no-such-lib.dll' (The specified module could not be found)
FFI\Exception: Failed resolving C function 'no_such_function'
FFI\Exception: C array index out of bounds
That's where the safety net ends. FFI trusts your declarations: if a prototype doesn't match the real function (wrong argument type, wrong struct layout, int where the library uses long long), or C writes past a buffer, the result is garbage or a crash of the whole PHP process, not an exception.
Wrapping a library in a PHP class
Don't spread CData objects through your application. Hide the FFI calls behind a small class with ordinary PHP types, so callers never deal with C memory:
<?php
declare(strict_types=1);
final class Geom
{
private static ?FFI $ffi = null;
private static function ffi(): FFI
{
return self::$ffi ??= FFI::cdef(<<<'C'
typedef struct { double x; double y; } Point;
double distance(Point a, Point b);
double sum(const double *values, size_t count);
char *greet(const char *name);
void free_string(char *s);
C, __DIR__ . '/' . match (PHP_OS_FAMILY) {
'Windows' => 'geom.dll',
'Darwin' => 'libgeom.dylib',
default => 'libgeom.so',
});
}
/** @param array{float, float} $a @param array{float, float} $b */
public static function distance(array $a, array $b): float
{
$ffi = self::ffi();
$pa = $ffi->new('Point');
[$pa->x, $pa->y] = $a;
$pb = $ffi->new('Point');
[$pb->x, $pb->y] = $b;
return $ffi->distance($pa, $pb);
}
/** @param list<float> $values */
public static function sum(array $values): float
{
$n = count($values);
if ($n === 0) {
return 0.0;
}
$ffi = self::ffi();
$arr = $ffi->new("double[$n]");
$bytes = pack('d*', ...$values);
FFI::memcpy($arr, $bytes, strlen($bytes));
return $ffi->sum($arr, $n);
}
public static function greet(string $name): string
{
$ffi = self::ffi();
$p = $ffi->greet($name);
try {
return FFI::string($p);
} finally {
$ffi->free_string($p);
}
}
}
var_dump(Geom::distance([1, 1], [4, 5]));
var_dump(Geom::sum([0.1, 0.2, 0.3]));
var_dump(Geom::sum([]));
var_dump(Geom::greet('wrapper'));
Output:
float(5)
float(0.6000000000000001)
float(0)
string(15) "Hello, wrapper!"
The library is loaded lazily once, try/finally guarantees the C string is freed, and sum() fills the C array with pack('d*', ...) + FFI::memcpy() instead of a PHP loop (see the benchmark below).
FFI::load, scopes and preloading
Parsing C declarations on every request costs time, and under ffi.enable=preload web requests can't call FFI::cdef() at all. The production setup is:
- Put the declarations in a header file with two special defines:
#define FFI_SCOPE "geom"
#define FFI_LIB "./libgeom.so"
typedef struct {
double x;
double y;
} Point;
double distance(Point a, Point b);
void translate(Point *p, double dx, double dy);
- Load it with
FFI::load()from an OPcache preload script:
<?php
// preload.php
// FFI_LIB is relative, and relative paths are resolved against the current directory
chdir(__DIR__);
FFI::load(__DIR__ . '/geom.h');
opcache.enable=1
opcache.preload=/var/www/app/preload.php
opcache.preload_user=www-data
ffi.enable=preload
- In request code, get the already parsed and loaded library by its scope name:
<?php
$geom = FFI::scope('geom');
$p = $geom->new('Point');
$p->x = 6; $p->y = 8;
echo $geom->distance($p, $geom->new('Point')), "\n";
Output, with preloading enabled (php -d opcache.enable_cli=1 -d opcache.preload=... t.php):
10
Without preloading, FFI::scope('geom') throws FFI\Exception: Failed loading scope 'geom'. FFI::load() also works outside preloading (it then behaves like FFI::cdef() with a file), which is handy in CLI scripts. Note that preloading isn't supported on Windows, where PHP prints Preloading is not supported on Windows; there you need ffi.enable=true to use FFI in web requests.
Performance
FFI isn't free. Every call converts arguments and goes through a generic call path, and every element access on a CData is a PHP operation. A benchmark with 1 million doubles (PHP 8.5, no JIT):
<?php
$ffi = FFI::cdef('double sum(const double *values, size_t count);', __DIR__ . '/geom.dll');
$n = 1_000_000;
$values = [];
for ($i = 0; $i < $n; $i++) $values[] = $i * 0.5;
$t = hrtime(true);
$total = array_sum($values);
printf("array_sum: %6.1f ms %.1f\n", (hrtime(true) - $t) / 1e6, $total);
$t = hrtime(true);
$arr = $ffi->new("double[$n]");
foreach ($values as $i => $v) $arr[$i] = $v;
$total = $ffi->sum($arr, $n);
printf("loop copy + C sum: %6.1f ms %.1f\n", (hrtime(true) - $t) / 1e6, $total);
$t = hrtime(true);
$arr = $ffi->new("double[$n]");
$bytes = pack('d*', ...$values);
FFI::memcpy($arr, $bytes, strlen($bytes));
$total = $ffi->sum($arr, $n);
printf("pack + memcpy + C sum: %6.1f ms %.1f\n", (hrtime(true) - $t) / 1e6, $total);
$t = hrtime(true);
$total = $ffi->sum($arr, $n);
printf("C sum only: %6.1f ms %.1f\n", (hrtime(true) - $t) / 1e6, $total);
// per-call overhead
$libc = FFI::cdef('size_t strlen(const char *s);', 'ucrtbase.dll');
$s = str_repeat('x', 100);
$t = hrtime(true);
for ($i = 0; $i < $n; $i++) strlen($s);
printf("1M x strlen(): %6.1f ms\n", (hrtime(true) - $t) / 1e6);
$t = hrtime(true);
for ($i = 0; $i < $n; $i++) $libc->strlen($s);
printf("1M x FFI strlen(): %6.1f ms\n", (hrtime(true) - $t) / 1e6);
Output:
array_sum: 4.0 ms 249999750000.0
loop copy + C sum: 26.9 ms 249999750000.0
pack + memcpy + C sum: 15.9 ms 249999750000.0
C sum only: 0.9 ms 249999750000.0
1M x strlen(): 15.5 ms
1M x FFI strlen(): 124.2 ms
The lessons:
- Calling a tiny C function through FFI is about 8x slower than calling a built-in PHP function. FFI doesn't make PHP code faster by replacing small functions.
- Moving data between PHP arrays and C memory dominates. Once the data is in C memory, C is fast (0.9 ms vs 4 ms), but copying it there cost 15-27 ms.
- FFI pays off when one call does a lot of work (image processing, compression, a solver, a database engine) or when there's simply no other way to reach the library. Keep data on the C side across calls and cross the boundary rarely.
Writing a native extension
A native extension is C code compiled against PHP's own headers. It registers functions and classes that look exactly like built-ins: real type declarations, reflection, TypeError/ValueError, no CData conversions. It's more work and must be compiled for each PHP version (and for ZTS/NTS builds), but it's the fastest option and works with any ffi.enable setting.
A complete minimal extension, fastmath, with two functions:
php_fastmath.h:
#ifndef PHP_FASTMATH_H
#define PHP_FASTMATH_H
extern zend_module_entry fastmath_module_entry;
#define phpext_fastmath_ptr &fastmath_module_entry
#define PHP_FASTMATH_VERSION "0.1.0"
#endif
fastmath.c:
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#include "ext/standard/info.h"
#include "php_fastmath.h"
/* function fastmath_sum(array $values): float */
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_fastmath_sum, 0, 1, IS_DOUBLE, 0)
ZEND_ARG_TYPE_INFO(0, values, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
/* function fastmath_clamp(int $value, int $min, int $max): int */
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_fastmath_clamp, 0, 3, IS_LONG, 0)
ZEND_ARG_TYPE_INFO(0, value, IS_LONG, 0)
ZEND_ARG_TYPE_INFO(0, min, IS_LONG, 0)
ZEND_ARG_TYPE_INFO(0, max, IS_LONG, 0)
ZEND_END_ARG_INFO()
PHP_FUNCTION(fastmath_sum)
{
HashTable *values;
zval *entry;
double total = 0.0;
ZEND_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY_HT(values)
ZEND_PARSE_PARAMETERS_END();
ZEND_HASH_FOREACH_VAL(values, entry) {
total += zval_get_double(entry);
} ZEND_HASH_FOREACH_END();
RETURN_DOUBLE(total);
}
PHP_FUNCTION(fastmath_clamp)
{
zend_long value, min, max;
ZEND_PARSE_PARAMETERS_START(3, 3)
Z_PARAM_LONG(value)
Z_PARAM_LONG(min)
Z_PARAM_LONG(max)
ZEND_PARSE_PARAMETERS_END();
if (min > max) {
zend_argument_value_error(2, "must be less than or equal to argument #3 ($max)");
RETURN_THROWS();
}
RETURN_LONG(value < min ? min : (value > max ? max : value));
}
static const zend_function_entry fastmath_functions[] = {
PHP_FE(fastmath_sum, arginfo_fastmath_sum)
PHP_FE(fastmath_clamp, arginfo_fastmath_clamp)
PHP_FE_END
};
PHP_MINFO_FUNCTION(fastmath)
{
php_info_print_table_start();
php_info_print_table_row(2, "fastmath support", "enabled");
php_info_print_table_row(2, "version", PHP_FASTMATH_VERSION);
php_info_print_table_end();
}
zend_module_entry fastmath_module_entry = {
STANDARD_MODULE_HEADER,
"fastmath", /* extension name */
fastmath_functions, /* functions */
NULL, /* MINIT */
NULL, /* MSHUTDOWN */
NULL, /* RINIT */
NULL, /* RSHUTDOWN */
PHP_MINFO(fastmath), /* phpinfo() section */
PHP_FASTMATH_VERSION,
STANDARD_MODULE_PROPERTIES
};
#ifdef COMPILE_DL_FASTMATH
ZEND_GET_MODULE(fastmath)
#endif
The pieces:
- arginfo describes the PHP signature (parameter names and types, return type) for reflection and type checks. In php-src and generated skeletons it's produced from a
fastmath.stub.phpfile bybuild/gen_stub.php; for a small extension, writing it by hand is fine. PHP_FUNCTIONbodies use the fast ZPP macros (ZEND_PARSE_PARAMETERS_START,Z_PARAM_*) to parse arguments. They throw the standardTypeErroron bad input.zend_argument_value_error()+RETURN_THROWS()throws aValueErrorthe same way built-in functions do.zend_module_entryties it together.MINIT/RINIThooks run on module and request startup when you need to register classes, constants orphp.inisettings.
The build configuration for Unix, config.m4:
PHP_ARG_ENABLE([fastmath],
[whether to enable fastmath support],
[AS_HELP_STRING([--enable-fastmath], [Enable fastmath support])],
[no])
if test "$PHP_FASTMATH" != "no"; then
PHP_NEW_EXTENSION([fastmath], [fastmath.c], [$ext_shared])
fi
and for Windows, config.w32:
ARG_ENABLE("fastmath", "fastmath support", "no");
if (PHP_FASTMATH != "no") {
EXTENSION("fastmath", "fastmath.c");
}
Build and install it with the standard tools from the php-dev package (on Windows: the PHP SDK binary tools plus the PHP development pack, then phpize.bat, configure.bat --enable-fastmath, nmake):
phpize
./configure --enable-fastmath
make
make test # runs tests/*.phpt, if any
sudo make install # copies fastmath.so into `php-config --extension-dir`
echo "extension=fastmath" | sudo tee /etc/php/8.5/mods-available/fastmath.ini
For a new extension, php ext/ext_skel.php --ext fastmath in a php-src checkout generates all of these files, including a stub file and test skeleton.
Using it:
<?php
var_dump(extension_loaded("fastmath"));
var_dump(fastmath_sum([1, 2.5, "3.5"]));
var_dump(fastmath_clamp(150, 0, 100));
try {
fastmath_clamp(5, 10, 1);
} catch (ValueError $e) {
echo get_class($e), ": ", $e->getMessage(), "\n";
}
try {
fastmath_sum("nope");
} catch (TypeError $e) {
echo get_class($e), ": ", $e->getMessage(), "\n";
}
$f = new ReflectionFunction("fastmath_clamp");
echo $f, "\n";
$ php -d extension=./modules/fastmath.so test.php
bool(true)
float(7)
int(100)
ValueError: fastmath_clamp(): Argument #2 ($min) must be less than or equal to argument #3 ($max)
TypeError: fastmath_sum(): Argument #1 ($values) must be of type array, string given
Function [ <internal:fastmath> function fastmath_clamp ] {
- Parameters [3] {
Parameter #0 [ <required> int $value ]
Parameter #1 [ <required> int $min ]
Parameter #2 [ <required> int $max ]
}
- Return [ int ]
}
php --re fastmath lists everything the extension registers and php --ri fastmath prints its phpinfo() section:
$ php -d extension=./modules/fastmath.so --ri fastmath
fastmath
fastmath support => enabled
version => 0.1.0
The functions are indistinguishable from built-ins: <internal:fastmath>, typed parameters, standard error messages. Extensions can also be distributed and installed with PIE (pie install vendor/package), the Composer-based successor of PECL.
FFI or extension?
| FFI | Native extension | |
|---|---|---|
| Write code in | PHP + C declarations | C against the Zend API |
| Compile step | only the C library (if it's yours) | for every PHP version, ZTS/NTS and OS |
| Call overhead | high (~100 ns per call) | same as built-in functions |
| PHP integration | CData values, manual conversions |
native types, classes, reflection, php.ini settings |
| Safety | wrong declarations crash the process | bugs crash the process |
| Deployment | ffi extension + ffi.enable / preloading |
install .so/.dll, extension= in php.ini |
| Good for | prototyping, calling existing C libraries and OS APIs, coarse-grained calls | widely used libraries, hot paths, deep integration |
A third option is often the simplest: run the native code as a separate process (a CLI tool called with proc_open(), or a small service over HTTP or a socket). It's slower per call, but a crash can't take PHP down and you can write it in any language.
Summary
- FFI is enabled with
extension=ffi; by default (ffi.enable=preload) it works in the CLI and in preloaded code only. FFI::cdef($decls, $lib)declares C functions and types without the preprocessor; call functions as methods on the returned object.- Create C values with
$ffi->new()and convert with$ffi->cast()(the static versions are deprecated); useFFI::addr(),FFI::string(),FFI::memcpy()andFFI::sizeof()to work with them. $ffi->new()memory is freed automatically;new($type, false)needsFFI::free(); memory from C'smalloc()must be freed by the C library.- PHP closures can be C callbacks; catch exceptions inside them.
- In production, put declarations in a header with
FFI_SCOPE/FFI_LIB, load it withFFI::load()from an OPcache preload script and useFFI::scope()(not available on Windows). - FFI calls have significant overhead; make few calls that each do a lot of work, and keep the data in C memory.
- Native extensions integrate perfectly and are the fastest, at the cost of writing Zend API C code and compiling per PHP build.