PHP to rust FFI example

This commit is contained in:
Nicolas Far
2019-05-17 19:14:20 -04:00
parent 0d944bd327
commit 21390884d1
5 changed files with 41 additions and 0 deletions

8
php-to-rust/Cargo.toml Normal file
View File

@@ -0,0 +1,8 @@
[package]
name = "php-to-rust"
version = "0.1.0"
authors = ["Nicolas Far <nicofff@gmail.com>"]
[lib]
name = "double_input"
crate-type = ["dylib"]

14
php-to-rust/Makefile Normal file
View File

@@ -0,0 +1,14 @@
ifeq ($(shell uname),Darwin)
EXT := dylib
else
EXT := so
endif
all: target/debug/libdouble_input.$(EXT)
php src/ffi.php
target/debug/libdouble_input.$(EXT): src/lib.rs Cargo.toml
cargo build
clean:
rm -rf target

5
php-to-rust/README.md Normal file
View File

@@ -0,0 +1,5 @@
PHP 7.4 is needed
At time of writing, that means [compiling from source](https://github.com/php/php-src#building-php-source-code).
Make sure to pass --with-ffi as a parameter to ./configure

9
php-to-rust/src/ffi.php Normal file
View File

@@ -0,0 +1,9 @@
<?php
$libExtension = (PHP_OS_FAMILY == "Darwin" ? 'dylib' : 'so');
$ffi = FFI::cdef(
"int32_t double_input(int32_t input);",
"target/debug/libdouble_input.$libExtension");
var_dump($ffi->double_input(3));
?>

5
php-to-rust/src/lib.rs Normal file
View File

@@ -0,0 +1,5 @@
#[no_mangle]
pub extern fn double_input(input: i32) -> i32 {
input * 2
}