Skip to content
Advertisement

php-ffi: Assign char* of a struct

I’m trying to set the value of a char* of a struct. This is a basic example:

$ffi = FFI::cdef('typedef struct
    {
        const char *name;
    } example_t;');
    
$struct = $ffi->new('example_t');
$struct->name = 'Test';

// FFIException: Incompatible types when assigning to type 'char*' from PHP 'string'

I’m getting an exception: FFIException: Incompatible types when assigning to type 'char*' from PHP 'string'

My question is: How to set the char *name of a struct?

My dirty way was to make an array of chars, str_split the string and set the keys of the char array to the splitted characters.

FFI::arrayType(FFI::type('char'), [$length]);

but with this approach I have an issue with Null Terminated Strings and don’t know how to solve it as well.

P.S.: I’ve got just basic C knowledge.

Advertisement

Answer

The solution is:

$ffi = FFI::cdef('typedef struct
{          
  const char *name;
} example_t;');

$struct = $ffi->new('example_t');
$struct->name = $ffi->new('char[5]', 0);
FFI::memcpy($struct->name, 'Test', 4);
var_dump($struct);
FFI::free($struct->name);

Solution provided by Dmitry Stogov on https://github.com/dstogov/php-ffi/issues/40

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement