FFI::cast() from pointer returns new value instead of reference.
Description
Hi!
I'm also not sure it's a bug, but documentation says: FFI::cast() creates a new FFI\CData object, that references the same C data structure, but is associated with a different type.
The following code:
<?php
$val = FFI::new('char[8]');
FFI::memcpy($val, implode('', range('a', 'h')), 8);
var_dump($val);
$firstInt = FFI::cast('int32_t', $val);
var_dump($firstInt);
$firstInt->cdata = 0;
var_dump($val);
$secondInt = FFI::cast('int32_t', $val + 4);
var_dump($secondInt);
$secondInt->cdata = 0;
var_dump($val);
Resulted in this output:
object(FFI\CData:char[8])#1 (8) {
[0]=>
string(1) "a"
[1]=>
string(1) "b"
[2]=>
string(1) "c"
[3]=>
string(1) "d"
[4]=>
string(1) "e"
[5]=>
string(1) "f"
[6]=>
string(1) "g"
[7]=>
string(1) "h"
}
object(FFI\CData:int32_t)#2 (1) {
["cdata"]=>
int(1684234849)
}
object(FFI\CData:char[8])#1 (8) {
[0]=>
string(1) ""
[1]=>
string(1) ""
[2]=>
string(1) ""
[3]=>
string(1) ""
[4]=>
string(1) "e"
[5]=>
string(1) "f"
[6]=>
string(1) "g"
[7]=>
string(1) "h"
}
object(FFI\CData:int32_t)#4 (1) {
["cdata"]=>
int(721424396)
}
object(FFI\CData:char[8])#1 (8) {
[0]=>
string(1) ""
[1]=>
string(1) ""
[2]=>
string(1) ""
[3]=>
string(1) ""
[4]=>
string(1) "e"
[5]=>
string(1) "f"
[6]=>
string(1) "g"
[7]=>
string(1) "h"
}
But I expected this output instead:
object(FFI\CData:char[8])#1 (8) {
[0]=>
string(1) "a"
[1]=>
string(1) "b"
[2]=>
string(1) "c"
[3]=>
string(1) "d"
[4]=>
string(1) "e"
[5]=>
string(1) "f"
[6]=>
string(1) "g"
[7]=>
string(1) "h"
}
object(FFI\CData:int32_t)#2 (1) {
["cdata"]=>
int(1684234849)
}
object(FFI\CData:char[8])#1 (8) {
[0]=>
string(1) ""
[1]=>
string(1) ""
[2]=>
string(1) ""
[3]=>
string(1) ""
[4]=>
string(1) "e"
[5]=>
string(1) "f"
[6]=>
string(1) "g"
[7]=>
string(1) "h"
}
object(FFI\CData:int32_t)#4 (1) {
["cdata"]=>
int(721424396)
}
object(FFI\CData:char[8])#1 (8) {
[0]=>
string(1) ""
[1]=>
string(1) ""
[2]=>
string(1) ""
[3]=>
string(1) ""
[4]=>
string(1) ""
[5]=>
string(1) ""
[6]=>
string(1) ""
[7]=>
string(1) ""
}
PHP Version
PHP 8.1.1
Operating System
No response
The first cast in the given script is from char[8] to int32_t which is guaranteed to be valid (i.e. could not possibly work on unallocated memory). The second cast is from char* to int32_t so could possibly manipulate unallocated memory (there is no guarantee that the pointer points to allocated memory). Since #7867 has been fixed, you could work around:
$secondInt = FFI::cast('int32_t', FFI::cast('char[4]', $val + 4));
what has the desired effect. So I tend to agree that the current behavior is a bug, or at least the behavior is not desireable.