[php-src] Issue #7866: Ability to pick PHP value by reference in FFI.
| From: | KapitanOczywisty | Date: | Thu, 03 Feb 2022 02:30:38 +0000 |
| Subject: | [php-src] Issue #7866: Ability to pick PHP value by reference in FFI. | ||
| Groups: | php.bugs | ||
| Request: | Send a blank email to php-bugs+get-239428@lists.php.net to get a copy of this message | ||
Issue: https://github.com/php/php-src/issues/7866
Comment Author: KapitanOczywisty
Cast from string would be very helpful, for example I have library which requires
**char parameter, and I'm not aware of any way to make that cast without copying
string or abusing FFI.
```php
$str = "hello world! hello world! hello world!";
$strlen = strlen($str);
// boring and slow copy
$strPtr = FFI::new("char[" . $strlen . "]");
FFI::memcpy($strPtr, $str, $strlen);
var_dump(FFI::cast("void *", $strPtr));
// abusing c functions
$libc = FFI::cdef(
'void * memset ( void * ptr, int value, size_t num );',
PHP_OS_FAMILY === 'Windows' ? 'VCRUNTIME140.dll' : 'libc.so.6'
);
$strPtr = $libc->memset($str, 0, 0);
var_dump($strPtr);
// abusing callbacks
$call = FFI::new("struct { char* (*ptr)(char str[]); }");
$call->ptr = function (\FFI\CData $str) : \FFI\CData {
return $str;
};
$ptrStruct = $call->ptr;
$strPtr = $ptrStruct($str);
var_dump(FFI::cast("void *", $strPtr));
var_dump(FFI::cast("void **", FFI::addr($strPtr)));
var_dump(($strPtr + 4)[0]);
```
```
object(FFI\CData:void*)#12 (1) {
[0]=>
int(2473465551440)
}
object(FFI\CData:void*)#5 (1) {
[0]=>
int(2473464960728)
}
object(FFI\CData:void*)#5 (1) {
[0]=>
int(2473464960728)
}
object(FFI\CData:void**)#15 (1) {
[0]=>
object(FFI\CData:void*)#5 (1) {
[0]=>
int(2473464960728)
}
}
string(1) "o"
```