Creating FFI Instances

Learn how to create and utilize various types of FFI instances in PHP 8.

Let’s have a look at creating and using FFI instances.

Creating and using FFI\CType instances

It’s extremely important to note that once the FFI\CType instance has been created, do not simply assign a value to it as if it were a native PHP variable. Doing so would simply overwrite the FFI\CType instance due to the fact that PHP is loosely typed. Instead, to assign a scalar value to an FFI\CType instance, use its cdata property.

The following example creates a $arr C array. The native C array is then populated with values up to its maximum size, after which we use a simple var_dump() to view its contents. We will proceed as follows:

Press + to interact
<?php
// long form:
//$type = FFI::arrayType(FFI::type("char"), [3, 3]);
//$arr = FFI::new($type);
// short syntax:
$arr = FFI::new(FFI::type("char[3][3]"));
// work with it like with a regular PHP array
$pos = 0;
$val = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$y_max = count($arr);
for ($y = 0; $y < $y_max; $y++) {
$x_max = count($arr[$y]);
for ($x = 0; $x < $x_max; $x++) {
$arr[$y][$x]->cdata = $val[$pos++];
}
echo FFI::string($arr[$y], 3) . "\n";
}
// use FFI::string() to display one of the rows
echo FFI::string($arr[0], 3) . "\n";
// TypeError: implode(): Argument #2 ($array) must be of type ?array, FFI\CData given in /repo/ch04/php8_ffi_array.php:29
try {
// NOTE: $arr is *not* an array!
echo implode(',', $arr);
} catch (Throwable $t) {
echo $t;
}
echo "\n";
?>

Let’s dive into the code,

  • Line 3–4: First, we create the array using FFI::arrayType(). As arguments, we supply a FFI::type() method and dimensions. We then use FFI::new() to create the FFI\Ctype instance. ...