Skip to content

Instantly share code, notes, and snippets.

@dirx
Last active January 5, 2020 11:15
Show Gist options
  • Save dirx/964cd6c00e6f8900962c65c9ac733737 to your computer and use it in GitHub Desktop.
Save dirx/964cd6c00e6f8900962c65c9ac733737 to your computer and use it in GitHub Desktop.
PHP 7.4 FFI and function pointers via dlsym
<?php
declare(strict_types=1);
// see http://manpages.ubuntu.com/manpages/bionic/man3/dlsym.3.html
$ffi = FFI::cdef(
"void *dlsym(void *handle, const char *symbol);"
);
$pointer = $ffi->dlsym(null, 'zend_write'); // it´s echo ...
$zend_write = FFI::new('void*(*)(...)'); // generic function pointer
FFI::memcpy(
FFI::addr($zend_write),
$pointer, // pointer to the function pointer
FFI::sizeof($zend_write)
);
$zend_write('hello world' . PHP_EOL, 12);
// do the same via ffi binding
$php = FFI::cdef(
"
typedef int (*zend_write_func_t)(const char *str, size_t str_length);
extern zend_write_func_t zend_write;
"
);
$zend_write_ffi = $php->zend_write;
var_dump($zend_write_ffi == $zend_write);
$zend_write_ffi('hello world ffi' . PHP_EOL, 16);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment