[php-src] Issue #7866: Allowing to pick PHP value by referenct in FFI.
| From: | userqq | Date: | Sat, 01 Jan 2022 14:29:51 +0000 |
| Subject: | [php-src] Issue #7866: Allowing to pick PHP value by referenct in FFI. | ||
| Groups: | php.bugs | ||
| Request: | Send a blank email to php-bugs+get-238700@lists.php.net to get a copy of this message | ||
Issue: https://github.com/php/php-src/issues/7866
Author: userqq
### Description
HI!
Currently the only way convert php value to FFI value is memcpy (or other ways with memory copying
involved).
It could be wasting if we for example received large chunk from socket and need to deal with it
through FFI.
For example,
```php
/* Initial */
echo memory_get_usage(); // 348504
/* Got chunk of data */
$data = str_repeat('1', 512 << 10);
echo memory_get_usage(); // 876992
/* Defining the FFI type */
$type = FFI::arrayType(FFI::type('char'), [512 << 10]);
echo memory_get_usage(); // 877184
/* Allocating memory for type */
$ffiValue = FFI::new($type);
echo memory_get_usage(); // 1401984
/* And memcpy */
FFI::memcpy($ffiValue, $data, 512 << 10);
echo memory_get_usage(); 1402048
```
It would be great to have ability to reflect value from PHP to FFI using it by reference like so:
```php
$data = str_repeat('1', 512 << 10);
/* @var FFI\CData $ffiValue */
$ffiValueCharArray = FFI::represent('char[]', &$data, size: 512 << 10); // No
additional memory allocations for $data content
$ffiValueCharArray [1] = 5;
var_dump($data[1]); // $data changed by reference
$ffiValueInt32 = FFI::represent('int32_t', &$data, size: 4, offset: 12);
$ffiValueInt32->cdata = 10;
var_dump(bin2hex(substr($data, 12, 4))); // "0a000000"
```