小编zor*_*mba的帖子

PHP FFI - 将 Rust 函数的数组返回给 PHP

我需要从 Rust 函数返回几个值。试图声明返回数组的函数

$ffi = FFI::cdef('float get_arr()[2];', './target/release/libphp_rust.dylib');

$array = $ffi->get_arr();
Run Code Online (Sandbox Code Playgroud)

但出现错误: PHP Fatal error: Uncaught FFI\ParserException: function returning array is not allowed at line 1 in /array.php:3

PHP FFI 似乎无法直接使用数组。所以我找到了另一个解决方案。我从 PHP 创建了 C 数组,然后将指向它的指针传递给 Rust 代码,然后用 Rust 函数填充它:

$ffi = FFI::cdef('bool get_arr(float (*res)[2]);', './target/release/libphp_rust.dylib');

$array = $ffi->new('float[2]');

$result = $ffi->get_arr(FFI::addr($array));

if ($result) {
    var_dump($array);
} else {
    //... something went wrong
}
Run Code Online (Sandbox Code Playgroud)
#[no_mangle]
pub extern fn get_arr(array_pointer: *mut [f32;2]) -> bool {
    let res = unsafe {
        assert!(!array_pointer.is_null());
        &mut …
Run Code Online (Sandbox Code Playgroud)

php ffi rust php-ffi

5
推荐指数
1
解决办法
665
查看次数

标签 统计

ffi ×1

php ×1

php-ffi ×1

rust ×1