Skip to content
Advertisement

php-ffi: Return type const char* is a string

Why is the result of const char * a string and char * an object „byte-array“?

A simple example:

$ffi = FFI::cdef(
  "const char *strerror(int errnum);",
  "libc.so.6"
);
var_dump($ffi->strerror(1));

returns

string(23) "Operation not permitted"

Removing const from the definition returns:

object(FFICData:char*)#1074 (1) {
  [0]=>
  string(1) "O"
}

Background

A function of a dynamically linked external C library returns binary data which include NULL-bytes. When const is in the definition of the header file the resulting string is not complete = shortened to the first NULL-byte = corrupt file.

My workaround

Remove const from the definition and

$array = $ffi->strerror(1);
$string = FFI::string($array);

returns the correct complete string.

(In the real-life scenario the $size for FFI::string($array, $size) is known and returned back from a different function of the C library.)

Advertisement

Answer

Dropping const or adding unsigned in the definition seem to be reasonable workarounds (cf. https://github.com/dstogov/php-ffi/issues/42#issuecomment-791237784)

Examples

Dropping const

$ffi = FFI::cdef(
  "char *strerror(int errnum);",
  "libc.so.6"
);
$array = $ffi->strerror(1);
$string = FFI::string($array);
var_dump($string);

Adding unsigned (or changing to uint8_t)

$ffi = FFI::cdef(
  "const unsigned char *strerror(int errnum);",
  "libc.so.6"
);
$byteArray = $ffi->strerror(1);
$charType = FFI::type('char*');
$castedValue = FFI::cast($charType, $byteArray);
$string = FFI::string($castedValue);
var_dump($string);
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement