Skip to content
Advertisement

PHP FFI – return array rom Rust function back to PHP

I need to return few values from rust function. Tried to declare function which returns an array

JavaScript

But got an error: PHP Fatal error: Uncaught FFIParserException: function returning array is not allowed at line 1 in /array.php:3

It seems PHP FFI can’t work with arrays directly. So I found another solution. I created C-array from PHP, then passed pointer to it to Rust code and then populated it with Rust function:

JavaScript
JavaScript

This solutions seems to work correct but i have some doubts about it:

  1. Is passing pointers to FFI safe enough and what problems may I face with this in future?
  2. Are Rust arrays fully C-compatible so that I’m able to assign value to it directly by index?
  3. I there better way to achieve what I need? Or maybe are there some good practices about passing complex data structures with FFI?

Thanks

Advertisement

Answer

The rules surrounding this are still up in the air, so your example is questionably safe. This should be ok, but requires nightly features:

JavaScript

On the stable channel it’s just less elegant:

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