Feature: PHP 7.4 Foreign Function Interface (FFI)


#1

Add FFI (Foreign Function Interface) to PHP 7.4

Currently testing the Foreign Function Interface module for PHP 7.4.
The PR is available and will have to go through CI before merging:

There’s also a current discussion on reddit regarding features of PHP 7.4:

Description

FFI PHP extension provides a simple way to call native functions, access native variables and create/access data structures defined in C language. The API of the extension is very simple and demonstrated by the following example and its output.

<?php
$libc = FFI::cdef("
    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);
", "libc.so.6");

$libc->printf("Hello World from %s!\n", "PHP");
var_dump($libc->getenv("PATH"));
var_dump($libc->time(null));

$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);
?>

Examples

Let me know of any examples you’ve below.


#2

FFI available

PR has been merged and is available.

Usage

  1. Select PHP 7.4
  2. Create custom ini file in cfg/php-ini-7.4/ffi.ini
ffi.enable = 1

I will also make the second step obsolete, as the module is enabled by default and this is currently only a safeguard by the module itself. I will keep you updated on this

Example

The most simple example creates an integer array in C and uses it in PHP:

<?php
$p = FFI::new("int[2]");
$p[0] = 1;
$p[1] = 2;
foreach ($p as $key => $val) {
	echo "$key => $val\n";
}