Hello All, I'd like to start a discussion around an FFI RFC
FFI RFC ====== There are many languages that support an FFI implementation. NodeJS Python C++ Ruby FFI allows you to call a native C function without requiring the boilerplate of an extension to be written. There are several benefits to having FFI - Performance - Shareability / Bundling - Common functionality between languages Performance === Although less pronounced than the 5.x versions, there is still a performance benefit to having native C code over PHP code. For example, you could utilise threading inside of your FFI methods, which PHP does not expose the ability to do. Shareability === If you wish to implement some of your source code in C, the current way to share it is to build it as an extension. This is cumbersome, and restricts use-cases such as shared hosting, where the ability to install your own extensions is probably restricted. However, with FFI, the shared object can be loaded from any location, and so that restriction is no longer in place. They could even be distributed via composer. Common functionality between languages === If you have some complex logic that needs to be replicated in several languages for whatever reason; implementing it several times over would lead to uncertain bugs and technical debt increasing heavily. If you could share the same logic amongst them all using FFI, then this is no longer an issue. Example === Take an example of a rust program that takes two numbers in and gives you the sum of them. ```rust #[no_mangle] pub extern fn add(a: i32, b: i32) -> i32 { a + b } ``` with the Cargo.toml file containing: ``` [package] name = "math" version = "0.1.0" authors = ["Alex Bowers <bowersb...@gmail.com>"] [dependencies] [lib] name = "math" crate-type = ["dylib"] ``` `cargo build --release` will create `.so`, `.dylib`, or `.dll` files depending on your system. These should be usable within PHP using the exposed functions. ```php $math = ffi("/path/to/math.so"); $result = $math->add(1, 5); echo $result; // 6 ``` With the implementation at its most basic level, calling the `add` method with incorrect parameters would likely cause a segfault. A way around that could be that the methods are not immediately exposed, but have to be configured. Something like: ```php $math = ffi("/path/to/math.so"); $math->add(1, 5); // Throws RuntimeException, method not configured $math->configure('add', int $a, int $b); $math->add(1, 5); // 6 $math->add('a', 5); Fatal error: Uncaught TypeError: Argument 1 passed to add() must be of the type integer, string given ``` Prior art: === https://pecl.php.net/package/ffi - Last release > 13 years https://github.com/mgdm/MFFI - Not stable, last commit > 1 year, no releases