Search⌘ K
AI Features

Solution: Data Manipulation of Foreign Function Interface in PHP

Explore how to manipulate data arrays using PHP 8's Foreign Function Interface. Learn to create, populate, and compare character arrays, and understand memory size and alignment functions. This lesson equips you with practical skills to make direct C calls in PHP efficiently.

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

PHP
<?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 ...