Created
February 28, 2023 15:24
-
-
Save sj-i/85926db98198e9f47dc540c9d1a6b3da to your computer and use it in GitHub Desktop.
Example of creating a C structure with a function pointer via FFI, setting a PHP callback to that function pointer and calling it via FFI, and calling other PHP callbacks from within it
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use FFI\CData; | |
$ffi = FFI::cdef( | |
<<<CDEF | |
typedef void (*func)(void (*callable1)(void), const char *(*callable2)(const char *)); | |
struct tmp { | |
func fp; | |
}; | |
CDEF | |
); | |
$tmp = $ffi->new('struct tmp'); | |
$tmp->fp = function (callable $callable1, callable $callable2): void { | |
$callable1(); | |
var_dump($callable2('foo')); | |
}; | |
$return = FFI::new('char[' . strlen('foo') + 1 . ']', false); | |
($tmp->fp)(function (): void {}, function (string $s) use ($return): CData { | |
FFI::memcpy($return, $s, strlen($s)); | |
$return[strlen($s)] = "\0"; | |
return $return; | |
}); | |
FFI::free($return); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment