Using PHP 8.0 FFI Extension to Integrate C Libraries
This article introduces PHP 8.0's built‑in FFI extension, explains its key features, demonstrates how to compile a simple C library into a shared object, and shows step‑by‑step PHP code to load the library, call its functions, and display the results.
With the evolution of technology, developers often need to combine code written in different programming languages. Traditionally this required an intermediary such as a database or API gateway, but PHP 8.0 now provides a native solution: the Foreign Function Interface (FFI) extension.
FFI allows PHP code to call functions from libraries written in C, C++, Rust, Go, Swift, and other languages without writing a custom PHP extension or shared library. It is bundled with PHP, so no additional installation is required.
Key features of the FFI extension include:
Declaration and invocation of C functions directly from PHP.
Automatic type conversion between PHP and C types such as pointers, structs, and unions.
Dynamic loading of shared (or static) libraries.
Automatic generation of PHP bindings for types, methods, and constants defined in the loaded library.
Using FFI is advantageous because it enables high‑performance code—such as complex algorithms, data structures, or graphics renderers—to be reused in PHP without the overhead of writing and maintaining a separate extension.
Step 1: Write a simple C library and compile it into a shared object
#include <stdio.h>
int add(int a, int b) {
return a + b;
}
int sub(int a, int b) {
return a - b;
}Compile the library with GCC:
gcc -c addsub.c
gcc -shared -o libaddsub.so addsub.oStep 2: Load the shared library in PHP using FFI
<?php
// Define a struct (example only)
FFI::cdef("
typedef unsigned char u_int8_t;
typedef struct in6_addr {
union {
u_int8_t __u6_addr8[16];
uint16_t __u6_addr16[8];
uint32_t __u6_addr32[4];
} __in6_u;
} in6_addr;
");
// Load the compiled library
$ffi = FFI::load("./libaddsub.so");
// Call the functions
$a = 10;
$b = 5;
$c = $ffi->add($a, $b);
$d = $ffi->sub($a, $b);
// Output the results
echo "$a + $b = $c\n";
echo "$a - $b = $d\n";
?>Run the script from the terminal:
php math.phpThe expected output is:
10 + 5 = 15
10 - 5 = 5This demonstrates that the C functions have been successfully integrated and invoked from PHP.
Conclusion
The PHP 8.0 FFI extension provides a straightforward way to incorporate external C libraries into PHP applications, eliminating the need for custom extensions or separate shared libraries. By compiling a C library, loading it with FFI, and calling its functions, developers can leverage high‑performance native code within their PHP projects.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.