...

/

Solution: Data Manipulation of Foreign Function Interface in PHP

Solution: Data Manipulation of Foreign Function Interface in PHP

A detailed review of the solution to the previous challenge involving creation, comparing, and finding infrastructural details of the Forign function interface in PHP 8.

We'll cover the following...

The code widget below contains the solution to the challenge. We will also go through a step-by-step explanation of the solution.

Solution

Press + to interact
<?php
$a = FFI::new("char[6]");
$b = FFI::new("char[6]");
$c = FFI::new("char[6]");
$d = FFI::new("char[6]");
// populate with values
$populate = function ($cdata, $start, $offset, $num) {
// populate with alpha chars
for ($x = 0; $x < $num; $x++)
$cdata[$x + $offset] = chr($x + $offset + $start);
return $cdata;
};
$a = $populate($a, 65, 0, 6);
$b = $populate($b, 65, 0, 3);
$b = $populate($b, 85, 3, 3);
$c = $populate($c, 71, 0, 6);
$d = $populate($d, 71, 0, 6);
$patt = "%2s : %6s\n";
printf($patt, '$a', FFI::string($a, 6));
printf($patt, '$b', FFI::string($b, 6));
printf($patt, '$c', FFI::string($c, 6));
printf($patt, '$d', FFI::string($d, 6));
echo "\nUsing FFI::memcmp()\n";
$p = "%20s : %2d\n";
printf($p, 'memcmp($a, $b, 6)', FFI::memcmp($a, $b, 6));
printf($p, 'memcmp($c, $a, 6)', FFI::memcmp($c, $a, 6));
printf($p, 'memcmp($c, $d, 6)', FFI::memcmp($c, $d, 6));
// using FFI::memcmp() but not full length
echo "\nUsing FFI::memcmp() but not full length\n";
printf($p, 'memcmp($a, $b, 3)', FFI::memcmp($a, $b, 3));
echo "The size is: " . FFI::sizeof($a) . " bytes.\n";
echo "The alignment is of: " . FFI::alignof($a) . " bytes.\n";
?>

Let’s get into the code.

  • Lines 3–6: We create four FFI instances using the new() method to create arrays of characters ...