Ability to pick PHP value by reference in FFI.
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,
/* 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:
$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);
var_dump($ffiValueInt32->cdata); // substr($data, 12, 4) === "1111", we will get here 825307441
$ffiValueInt32->cdata = 10;
var_dump(bin2hex(substr($data, 12, 4))); // "0a000000"
Also could work not only with strings:
$int = 10;
$ffiValueInt64 = FFI::represent('int64_t', &$int); // length argument could be omitted if cast performed to fixed size type
var_dump($ffiValueInt64->cdata); // 10;
$ffiValueInt64->cdata = 20;
var_dump($int); // 20;
$readOverBoundary = FFI::represent('char[]', &$int, 10); // Exception: attempt to read over boundary
Hmm, you can pass a PHP string to a C char * without further ado (see https://www.php.net/manual/en/ffi.examples-basic.php). Wouldn't that work for you?
HI @cmb69, It could work in this case, thank you!
But in my case I using FFI without libraries, as alternative to unpack() - it seems faster to me, if I measured correctly.
E.g.:
$int = FFI::new('int32_t');
$data = fread($h, 4);
FFI::memcpy($int, $data, 4);
var_dump($int->cdata);
Or even with structs:
$header = FFI::new('struct {
int64_t authKeyId;
int64_t messageId;
int32_t length;
}');
$data = fread($h, 20);
FFI::memcpy($header, $data, 20);
var_dump($header->length);
And it would be great to have possibility to achive something like:
$data = fread($h, $packetLength);
// No data copied, $packet is reference to $data
$packet = FFI::represent('struct {
int64_t messageId;
int32_t length;
char payload[];
}', &$data, $packetLength);
var_dump($packet->length);
// Lets imagine payload is also binary packed struct
$message = FFI::represent('struct {
int32_t messageTypeId;
int32_t magic;
int32_t signature;
...
}', &$packet->payload, FFI::sizeof($packet->payload));
var_dump($message->messageTypeId);
// $message is reference to $packet, which is reference to $data
// Modification of $message should affect $data value
$message->magic = 200;
I see your point, but somehow this doesn't really look related to FFI (foreign function interface). It's more like an alternative to pack()/unpack(). I think there could be some function similar to unpack() which gives you a mutable object which works on the string data, instead of an unpacked array.
Thank you, it could be an option too. I think it would be great to have more convenient way to work with binary data. But since in FFI we are dealing with C types and all the binary protocols are representing those types in some way, I thought it would be nice to have such possibility.
Anyway, since it seems like FFI::cast to array types most likely will be fixed, it not an issue anymore and I have no objections if you close current issue.
@cmb69 @dstogov
Hmm, you can pass a PHP string to a C char * without further ado (see https://www.php.net/manual/en/ffi.examples-basic.php). Wouldn't that work for you?
If there is a possibility to pass PHP string to C function and modify string value inside C function by reference maybe then FFI::cast() could be allowed for strings in such way:
$string = 'aaaa';
$int = FFI::cast('int32_t', $string);
var_dump($int); /*
object(FFI\CData:int32_t)#3 (1) {
["cdata"]=>
int(1633771873)
} */
$chars = FFI::cast('char[4]', $string);
var_dump($chars); /*
object(FFI\CData:char[4])#1 (4) {
[0]=>
string(1) "a"
[1]=>
string(1) "a"
[2]=>
string(1) "a"
[3]=>
string(1) "a"
} */
$chars[2] = 'b';
var_dump($string); /* string(4) "aaba" */
var_dump($int); /*
object(FFI\CData:int32_t)#3 (1) {
["cdata"]=>
int(1633837409)
} */
$string = 'a';
FFI::cast('char[4]', $string); // FFI\Exception: attempt to cast to larger type
FFI::cast('char[4]', 'aaaa'); // Error: FFI::cast(): Argument #2 ($ptr) cannot be passed by reference
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.
$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
$struct = FFI::new("struct { char* (*ptr)(char str[]); }");
$struct->ptr = function (\FFI\CData $str) : \FFI\CData {
return $str;
};
$getPtr = $struct->ptr;
$strPtr = $getPtr($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"
With that pointer can be used to modify string:
$str = "hello world!";
$libc = FFI::cdef(
'void * memset ( void * ptr, int value, size_t num );
void * memcpy ( void * destination, const void * source, size_t num );',
PHP_OS_FAMILY === 'Windows' ? 'VCRUNTIME140.dll' : 'libc.so.6'
);
$strPtr = $libc->memset($str, 0, 0);
$libc->memcpy($strPtr + 6, "github", 6);
var_dump($str); // string(12) "hello github"
@KapitanOczywisty It' wonderful! Thank you for examples.
Could you please advise is there any known way to cast char reference with offset back to string without external libraries? For the last two monthes I'm looking for the way to get slice of string by ref but no luck yet.
@userqq php itself is using these functions, so they should be loaded anyway - at this very moment I think this is the fastest and safest option. You can use callback variant, but ffi has quite a few issues with them.
I think that string in FFI::cast should be treated as char[$strlen] or char*, thus FFI::cast('char*', $string) should be allowed. @cmb69 is this reasonable?