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: https://github.com/dstogov/php-ffi. 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.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);

//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"
int(1523617815)
int(1523617815)
int(977765)
object(FFI\CData:)#3 (2) {
  ["tz_minuteswest"]=>
  int(-180)
  ["tz_dsttime"]=>
  int(0)
}

Reference

PHP 7 News & Updates v7.0 - 7.4 - Book coverPHP 7 News & Updates v7.0 – 7.4 Book https://www.amazon.com/PHP-News-Updates-v7-0-7-4/dp/1727202481/

Rate this artcile
[Total: 1 Average: 5]