《PHP實例:在PHP程序中使用Rust擴展的方法》要點:
本文介紹了PHP實例:在PHP程序中使用Rust擴展的方法,希望對您有用。如果有疑問,可以聯系我們。
?C或PHP中的RustPHP教程
我的基本出發點便是寫一些可以編譯的Rust代碼到一個庫里面,并寫為它一些C的頭文件,在C中為被調用的PHP做一個拓展.雖然并不是很簡單,但是很有趣.
Rust FFI(foreign function interface)PHP教程
我所做的第一件事情就是擺弄Rust與C連接的Rust的外部函數接口.我曾用簡單的辦法(hello_from_rust)寫過一個靈活的庫,伴有單一的聲明(a pointer to a C char, otherwise known as a string),如下是輸入后輸出的“Hello from Rust”.
?
PHP教程
// hello_from_rust.rs #![crate_type = "staticlib"] #![feature(libc)] extern crate libc; use std::ffi::CStr; #[no_mangle] pub extern "C" fn hello_from_rust(name: *const libc::c_char) { let buf_name = unsafe { CStr::from_ptr(name).to_bytes() }; let str_name = String::from_utf8(buf_name.to_vec()).unwrap(); let c_name = format!("Hello from Rust, {}", str_name); println!("{}", c_name); }
我從C(或其它!)中挪用的Rust庫拆分它.這有一個接下來會怎樣的很好的解釋.PHP教程
編譯它會得到.a的一個文件,libhello_from_rust.a.這是一個靜態的庫,包括它自己所有的依賴關系,而且我們在編譯一個C程序的時候鏈接它,這讓我們能做后續的事情.注意:在我們編譯后會得到如下輸出:
?
PHP教程
note: link against the following native artifacts when linking against this static library note: the order and any duplication can be significant on some platforms, and so may need to be preserved note: library: Systemnote: library: pthread note: library: c note: library: m
這就是Rust編譯器在我們不使用這個依賴的時候所告訴我們必要鏈接什么.PHP教程
從C中挪用RustPHP教程
既然我們有了一個庫,不得不做兩件事來保證它從C中可調用.首先,我們必要為它創建一個C的頭文件,hello_from_rust.h.然后在我們編譯的時候鏈接到它.PHP教程
下面是頭文件:
?
PHP教程
// hello_from_rust.h #ifndef __HELLO #define __HELLO void hello_from_rust(const char *name); #endif
這是一個相當基礎的頭文件,僅僅為了一個簡單的函數提供簽名/定義.接著我們必要寫一個C程序并使用它.
?
PHP教程
// hello.c #include <stdio.h> #include <stdlib.h> #include "hello_from_rust.h" int main(int argc, char *argv[]) { hello_from_rust("Jared!"); }
我們通過運行一下代碼來編譯它:
?
PHP教程
gcc -Wall -o hello_c hello.c -L /Users/jmcfarland/code/rust/php-hello-rust -lhello_from_rust -lSystem -lpthread -lc -lm
注意在末尾的-lSystem -lpthread -lc -lm告訴gcc不要鏈接那些“當地的古董”,為了當編譯我們的Rust庫時Rust編譯器可以提供出來.PHP教程
經運行下面的代碼我們可以獲得一個二進制的文件:
?
PHP教程
$ ./hello_c Hello from Rust, Jared!
漂亮!我們剛才從C中調用了Rust庫.現在我們必要理解Rust庫是如何進入一個PHP擴展的.PHP教程
從 php 中挪用 cPHP教程
該部分花了我一些時間來弄明白,在這個世界上,該文檔在 php 擴展中并不是最好的.最好的部分是來自綁定一個腳本 ext_skel 的 php 源(大多數代表“擴展骨架”)即生成大多數你必要的樣板代碼.? 你可以通過下載來開始,和未配額的 php 源,把代碼寫進 php 目錄并且運行:PHP教程
$ cd ext/ $ ./ext_skel --extname=hello_from_rust
? 這將生成需要創建 php 擴展的基本骨架.現在,移動你處處想局部地堅持你的擴展的文件夾.并且移動你的PHP教程
進入同一個目次.因此,現在你應該看看像這樣的一個目次:PHP教程
. ├── CREDITS ├── EXPERIMENTAL ├── config.m4 ├── config.w32 ├── hello_from_rust.c ├── hello_from_rust.h ├── hello_from_rust.php ├── hello_from_rust.rs ├── libhello_from_rust.a ├── php_hello_from_rust.h └── tests └── 001.phpt
一個目次,11個文件PHP教程
你可以在 php docs 在上面看到關于這些文件很好的描述.建立一個擴展的文件.我們將通過編纂 config.m4 來開始吧.PHP教程
不解釋,下面便是我的成果:
?
PHP教程
PHP_ARG_WITH(hello_from_rust, for hello_from_rust support, [ --with-hello_from_rust Include hello_from_rust support]) if test "$PHP_HELLO_FROM_RUST" != "no"; then PHP_SUBST(HELLO_FROM_RUST_SHARED_LIBADD) PHP_ADD_LIBRARY_WITH_PATH(hello_from_rust, ., HELLO_FROM_RUST_SHARED_LIBADD) PHP_NEW_EXTENSION(hello_from_rust, hello_from_rust.c, $ext_shared) fi
正如我所理解的那樣,這些是基本的宏命令.但是有關這些宏命令的文檔是相當糟糕的(比如:google"PHP_ADD_LIBRARY_WITH_PATH"并沒有出現PHP團隊所寫的結果).我偶然這個PHP_ADD_LIBRARY_PATH宏命令在有些人所談論的在一個PHP拓展里鏈接一個靜態庫的先前的線程里.在評論中其它的保舉使用的宏命令是在我運行ext_skel后產生的.PHP教程
既然我們進行了配置設置,我們需要從PHP腳本中實際地調用庫.為此我們得修改自動生成的文件,hello_from_rust.c.首先我們添加hello_from_rust.h頭文件到包含命令中.然后我們要修改confirm_hello_from_rust_compiled的定義辦法.
?
PHP教程
#include "hello_from_rust.h" // a bunch of comments and code removed... PHP_FUNCTION(confirm_hello_from_rust_compiled) { char *arg = NULL; int arg_len, len; char *strg; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &arg, &arg_len) == FAILURE) { return; } hello_from_rust("Jared (from PHP!!)!"); len = spprintf(&strg, 0, "Congratulations! You have successfully modified ext/%.78s/config.m4. Module %.78s is now compiled into PHP.", "hello_from_rust", arg); RETURN_STRINGL(strg, len, 0); }
注意:我添加了hello_from_rust("Jared (fromPHP!!)!");.PHP教程
現在,我們可以試著樹立我們的擴展:PHP教程
$ phpize $ ./configure $ sudo make install
就是它,生成我們的元配置,運行生成的配置命令,然后安裝該擴展.安裝時,我必需親自使用sudo,因為我的用戶并不擁有安裝目錄的 php 擴展.PHP教程
現在,我們可以運行它啦!PHP教程
$ php hello_from_rust.php Functions available in the test extension: confirm_hello_from_rust_compiled Hello from Rust, Jared (from PHP!!)! Congratulations! You have successfully modified ext/hello_from_rust/config.m4. Module hello_from_rust is now compiled into PHP. Segmentation fault: 11
還不錯,php 已進入我們的 c 擴展,看到我們的應用辦法列表并且調用.接著,c 擴展已進入我們的 rust 庫,開始打印我們的字符串.那很有趣!但是......那段錯誤的結局發生了什么?PHP教程
正如我所提到的,這里是使用了 Rust 相關的 println! 宏,但是我沒有對它做進一步的調試.如果我們從我們的 Rust 庫中刪除并返回一個 char* 替代,段差錯就會消失.PHP教程
這里是 Rust 的代碼:
?PHP教程
并變革 C 頭文件:
?
PHP教程
#ifndef __HELLO #define __HELLO const char * hello_from_rust(const char *name); #endif
還要變革 C 擴展文件:
?
PHP教程
PHP_FUNCTION(confirm_hello_from_rust_compiled) { char *arg = NULL; int arg_len, len; char *strg; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &arg, &arg_len) == FAILURE) { return; } char *str; str = hello_from_rust("Jared (from PHP!!)!"); printf("%s\n", str); len = spprintf(&strg, 0, "Congratulations! You have successfully modified ext/%.78s/config.m4. Module %.78s is now compiled into PHP.", "hello_from_rust", arg); RETURN_STRINGL(strg, len, 0); }
無用的微基準PHP教程
那么為什么你還要這樣做?我還真的沒有在現實世界里使用過這個.但是我真的認為斐波那契序列算法便是一個好的例子來說明一個PHP拓展如何很基本.通常是直截了當(在Ruby中):
?
PHP教程
def fib(at) do if (at == 1 || at == 0) return at else return fib(at - 1) + fib(at - 2) end end
并且可以通過不使用遞歸來改善這不好的性能:
?
PHP教程
def fib(at) do if (at == 1 || at == 0) return at elsif (val = @cache[at]).present? return val end total = 1 parent = 1 gp = 1 (1..at).each do |i| total = parent + gp gp = parent parent = total end return total end
那么我們環抱它來寫兩個例子,一個在PHP中,一個在Rust中.看看哪個更快.下面是PHP版:
?
PHP教程
def fib(at) do if (at == 1 || at == 0) return at elsif (val = @cache[at]).present? return val end total = 1 parent = 1 gp = 1 (1..at).each do |i| total = parent + gp gp = parent parent = total end return total end
這是它的運行成果:
?
PHP教程
$ time php php_fib.php real 0m2.046s user 0m1.823s sys 0m0.207s
現在我們來做Rust版.下面是庫資源:
?PHP教程
注意,我編譯的庫rustc - O rust_lib.rs使編譯器優化(因為我們是這里的尺度).這里是C擴展源(相關摘錄):
?
PHP教程
PHP_FUNCTION(confirm_rust_fib_compiled) { long number; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &number) == FAILURE) { return; } RETURN_LONG(rust_fib(number)); }
運行PHP劇本:
?
PHP教程
<?php $br = (php_sapi_name() == "cli")? "":"<br>"; if(!extension_loaded('rust_fib')) { dl('rust_fib.' . PHP_SHLIB_SUFFIX); } for ($i = 0; $i < 100000; $i ++) { confirm_rust_fib_compiled(92); } ?>
這便是它的運行結果:
PHP教程
$ time php rust_fib.php real 0m0.586s user 0m0.342s sys 0m0.221s
你可以瞥見它比前者快了三倍!完美的Rust微基準!
PHP教程
歡迎參與《PHP實例:在PHP程序中使用Rust擴展的方法》討論,分享您的想法,維易PHP學院為您提供專業教程。