|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2020-01-21 22:04 UTC] flip101 at gmail dot com
Description: ------------ On example #5 in https://www.php.net/manual/en/ffi.examples-basic.php it says "work with it like with a regular PHP array". But when i assign values directly $a = [1, 2, 3, 4]; The type seems to change from `FFI\CData` to PHP `array`. It would be useful to have an array copy method so a copy loop (which seems?? the only way for the moment) doesn't need to be done in php itself. Although pack() could be used as well, but is that the best way? PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Sun Oct 26 07:00:01 2025 UTC |
I wrote this piece of code, not saying it's the best. But perhaps some of the logic here is better implemented in C. function arrayCreate(string $type, array $source) { $size = count($source); if ('char' === $type) { $format = 'c'; $bytes_multiplier = 1; } elseif ('unsigned char' === $type) { $format = 'C'; $bytes_multiplier = 1; } elseif ('short' === $type) { $format = 's'; $bytes_multiplier = 2; } elseif ('unsigned short' === $type) { $format = 'S'; $bytes_multiplier = 2; } elseif ('int' === $type) { $format = 'i'; $bytes_multiplier = 4; // assumption: https://stackoverflow.com/a/11438838/1833322 } elseif ('unsigned int' === $type) { $format = 'I'; $bytes_multiplier = 4; } elseif ('long' === $type) { $format = 'l'; $bytes_multiplier = 4; } elseif ('unsigned long' === $type) { $format = 'L'; $bytes_multiplier = 4; } elseif ('long long' === $type) { $format = 'q'; $bytes_multiplier = 8; } elseif ('unsigned long long' === $type) { $format = 'Q'; $bytes_multiplier = 8; } elseif ('float' === $type) { $format = 'f'; $bytes_multiplier = 4; } elseif ('double' === $type) { $format = 'd'; $bytes_multiplier = 8; } else { throw new \InvalidArgumentException('type'); } $first_type = gettype(reset($source)); if (! array_reduce($source, function($c, $i) use ($first_type) { return $c && gettype($i) === $first_type; }, true)) { throw new \InvalidArgumentException('source'); } $array = FFI::new($type . '[' . $size . ']'); FFI::memcpy($array, pack($format . '*', ...$source), $size * $bytes_multiplier); return $array; }