我正在嘗試設置結構體 char* 的值。這是一個基本示例:$ffi = FFI::cdef('typedef struct { const char *name; } example_t;'); $struct = $ffi->new('example_t');$struct->name = 'Test';// FFI\Exception: Incompatible types when assigning to type 'char*' from PHP 'string'我遇到了一個例外:FFI\Exception: Incompatible types when assigning to type 'char*' from PHP 'string'我的問題是:如何設置結構體的 char *name ?我的骯臟方法是創建一個字符數組,str_split字符串并將字符數組的鍵設置為分割的字符。FFI::arrayType(FFI::type('char'), [$length]);但通過這種方法,我遇到了空終止字符串的問題,并且也不知道如何解決它。PS:我只有基本的C知識。
1 回答

胡子哥哥
TA貢獻1825條經驗 獲得超6個贊
解決辦法是:
$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);
Dmitry Stogov 在https://github.com/dstogov/php-ffi/issues/40上提供的解決方案
- 1 回答
- 0 關注
- 141 瀏覽
添加回答
舉報
0/150
提交
取消