Call native C code in PHP – Foreign Function Interface

Call native C code in PHP – Foreign Function Interface

Foreign C language in PHP world

The Foreign Function Interface (FFI) is a simple way to call any native functions, access variables or create data structures defined in original C language.

The solution is in the experimental extension that could be already used in PHP 7.3+; the library is libffi and allows a high level languages to generate C code. The github page is: An example usage is provided below:

//php code
$libc = new FFI("
    //start of C code
    int printf(const char *format, ...);
    const char * getenv(const char *);
    unsigned int time(unsigned int *);

    typedef unsigned int time_t;
    typedef unsigned int suseconds_t;

    struct timeval {
        time_t      tv_sec;
        suseconds_t tv_usec;

    struct timezone {
        int tz_minuteswest;
        int tz_dsttime;

	int gettimeofday(struct timeval *tv, struct timezone *tz);
       //end of C code
", "");

$libc->printf("Hello World from %s!\n", "PHP");

$tv = $libc->new("struct timeval");
$tz = $libc->new("struct timezone");
$libc->gettimeofday(FFI::addr($tv), FFI::addr($tz));
var_dump($tv->tv_sec, $tv->tv_usec, $tz);

//will output
Hello World from PHP!
string(135) "/usr/lib64/qt-3.3/bin:/usr/lib64/ccache:/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/home/adam/.local/bin:/home/adam/bin"
object(FFI\CData:)#3 (2) {


PHP 7 News & Updates v7.0 - 7.4 - Book coverPHP 7 News & Updates v7.0 – 7.4 Book

Rate this artcile
[Total: 1 Average: 5]

Leave a Comment