使用 Rust 建立 PHP 擴充

來源:互聯網
上載者:User

去年十月,我和 Etsy 的同事有過一個關於如何為像PHP樣的解釋性語言寫拓展的討論,Ruby或Python目前的狀況應該會比PHP容易。我們談到了寫一個成功建立擴充的障礙是它們通常需要用C來寫,但是如果你不擅長C這門語言的話很難有那個信心。

從那時起我便萌生了用Rust寫一個的想法,過去的幾天一直在嘗試。今天上午我終於讓它運行了。
C或PHP中的Rust

我的基本出發點就是寫一些可以編譯的Rust代碼到一個庫裡面,並寫為它一些C的標頭檔,在C中為被調用的PHP做一個拓展。雖然並不是很簡單,但是很有趣。
Rust FFI(foreign function interface)

我所做的第一件事情就是擺弄Rust與C串連的Rust的外部函數介面。我曾用簡單的方法(hello_from_rust)寫過一個靈活的庫,伴有單一的聲明(a pointer to a C char, otherwise known as a string),如下是輸入後輸出的“Hello from Rust”。

 
  1. // hello_from_rust.rs 
  2. #![crate_type = "staticlib"] 
  3.  
  4. #![feature(libc)] 
  5. extern crate libc; 
  6. use std::ffi::CStr; 
  7.  
  8. #[no_mangle] 
  9. pub extern "C" fn hello_from_rust(name: *const libc::c_char) { 
  10. let buf_name = unsafe { CStr::from_ptr(name).to_bytes() }; 
  11. let str_name = String::from_utf8(buf_name.to_vec()).unwrap(); 
  12. let c_name = format!("Hello from Rust, {}", str_name); 
  13. println!("{}", c_name); 

我從C(或其它!)中調用的Rust庫拆分它。這有一個接下來會怎樣的很好的解釋。

編譯它會得到.a的一個檔案,libhello_from_rust.a。這是一個靜態庫,包含它自己所有的依賴關係,而且我們在編譯一個C程式的時候連結它,這讓我們能做後續的事情。注意:在我們編譯後會得到如下輸出:

 
  1. note: link against the following native artifacts when linking against this static library 
  2. note: the order and any duplication can be significant on some platforms, and so may need to be preserved 
  3. note: library: Systemnote: library: pthread 
  4. note: library: c 
  5. note: library: m 

這就是Rust編譯器在我們不使用這個依賴的時候所告訴我們需要連結什麼。
從C中調用Rust

既然我們有了一個庫,不得不做兩件事來保證它從C中可調用。首先,我們需要為它建立一個C的標頭檔,hello_from_rust.h。然後在我們編譯的時候連結到它。

下面是標頭檔:

 
  1. note: link against the following native artifacts when linking against this static library 
  2. note: the order and any duplication can be significant on some platforms, and so may need to be preserved 
  3. note: library: Systemnote: library: pthread 
  4. note: library: c 
  5. note: library: m 

這是一個相當基礎的標頭檔,僅僅為了一個簡單的函數提供簽名/定義。接著我們需要寫一個C程式並使用它。

 
  1. // hello.c 
  2. #include <stdio.h> 
  3. #include <stdlib.h> 
  4. #include "hello_from_rust.h" 
  5.  
  6. int main(int argc, char *argv[]) { 
  7. hello_from_rust("Jared!"); 

我們通過運行一下代碼來編譯它:

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編譯器可以提供出來。

經運行下面的代碼我們可以得到一個二進位的檔案:

 
  1. $ ./hello_c 
  2. Hello from Rust, Jared! 

漂亮!我們剛才從C中調用了Rust庫。現在我們需要理解Rust庫是如何進入一個PHP擴充的。

從 php 中調用 c

該部分花了我一些時間來弄明白,在這個世界上,該文檔在 php 擴充中並不是最好的。最好的部分是來自綁定一個指令碼 ext_skel 的 php 源(大多數代表“擴充骨架”)即產生大多數你需要的樣板代碼。為了讓代碼運行,我十分努力地學習 php 文檔,“擴充骨骼”。

你可以通過下載來開始,和未配額的 php 源,把代碼寫進 php 目錄並且運行:

 
  1. $ cd ext/ 
  2. $ ./ext_skel –extname=hello_from_rust 

這將產生需要建立 php 擴充的基本骨架。現在,移動你處處想局部地保持你的擴充的檔案夾。並且移動你的

.rust 源

.rust庫

.c header

進入同一個目錄。因此,現在你應該看看像這樣的一個目錄:

.
├── 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 docs 在上面看到關於這些檔案很好的描述。建立一個擴充的檔案。我們將通過編輯 config.m4 來開始吧。

不解釋,下面就是我的成果:

 
  1. PHP_ARG_WITH(hello_from_rust, for hello_from_rust support, 
  2. [ --with-hello_from_rust Include hello_from_rust support]) 
  3.  
  4. if test "$PHP_HELLO_FROM_RUST" != "no"; then 
  5. PHP_SUBST(HELLO_FROM_RUST_SHARED_LIBADD) 
  6.  
  7. PHP_ADD_LIBRARY_WITH_PATH(hello_from_rust, ., HELLO_FROM_RUST_SHARED_LIBADD) 
  8.  
  9. PHP_NEW_EXTENSION(hello_from_rust, hello_from_rust.c, $ext_shared) 
  10. fi 

正如我所理解的那樣,這些是基本的宏命令。但是有關這些宏命令的文檔是相當糟糕的(比如:google”PHP_ADD_LIBRARY_WITH_PATH”並沒有出現PHP團隊所寫的結果)。我偶然這個PHP_ADD_LIBRARY_PATH宏命令在有些人所談論的在一個PHP拓展裡連結一個靜態庫的先前的線程裡。在評論中其它的推薦使用的宏命令是在我運行ext_skel後產生的。

既然我們進行了配置設定,我們需要從PHP指令碼中實際地調用庫。為此我們得修改自動產生的檔案,hello_from_rust.c。首先我們添加hello_from_rust.h標頭檔到包含命令中。然後我們要修改confirm_hello_from_rust_compiled的定義方法。

 
  1. #include "hello_from_rust.h" 
  2.  
  3. // a bunch of comments and code removed... 
  4.  
  5. PHP_FUNCTION(confirm_hello_from_rust_compiled) 
  6. char *arg = NULL; 
  7. int arg_len, len; 
  8. char *strg; 
  9.  
  10. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &arg, &arg_len) == FAILURE) { 
  11. return; 
  12.  
  13. hello_from_rust("Jared (from PHP!!)!"); 
  14.  
  15. len = spprintf(&strg, 0, "Congratulations! You have successfully modified ext/%.78s/config.m4. Module %.78s is now compiled into PHP.", "hello_from_rust", arg); 
  16. RETURN_STRINGL(strg, len, 0); 

注意:我添加了hello_from_rust(“Jared (fromPHP!!)!”);。

現在,我們可以試著建立我們的擴充:

 
  1. $ phpize 
  2. $ ./configure 
  3. $ sudo make install 

就是它,產生我們的元配置,運行產生的配置命令,然後安裝該擴充。安裝時,我必須親自使用sudo,因為我的使用者並不擁有安裝目錄的 php 擴充。

現在,我們可以運行它啦!

 
  1. $ php hello_from_rust.php 
  2. Functions available in the test extension: 
  3. confirm_hello_from_rust_compiled 
  4.  
  5. Hello from Rust, Jared (from PHP!!)! 
  6. Congratulations! You have successfully modified ext/hello_from_rust/config.m4. Module hello_from_rust is now compiled into PHP. 
  7. Segmentation fault: 11 

還不錯,php 已進入我們的 c 擴充,看到我們的應用方法列表並且調用。接著,c 擴充已進入我們的 rust 庫,開始列印我們的字串。那很有趣!但是……那段錯誤的結局發生了什嗎?

正如我所提到的,這裡是使用了 Rust 相關的 println! 宏,但是我沒有對它做進一步的調試。如果我們從我們的 Rust 庫中刪除並返回一個 char* 替代,段錯誤就會消失。

這裡是 Rust 的代碼:

 
  1. #![crate_type = "staticlib"] 
  2.  
  3. #![feature(libc)] 
  4. extern crate libc; 
  5. use std::ffi::{CStr, CString}; 
  6.  
  7. #[no_mangle] 
  8. pub extern "C" fn hello_from_rust(name: *const libc::c_char) -> *const libc::c_char { 
  9. let buf_name = unsafe { CStr::from_ptr(name).to_bytes() }; 
  10. let str_name = String::from_utf8(buf_name.to_vec()).unwrap(); 
  11. let c_name = format!("Hello from Rust, {}", str_name); 
  12.  
  13. CString::new(c_name).unwrap().as_ptr() 

並變更 C 標頭檔:

 
  1. #ifndef __HELLO 
  2. #define __HELLO 
  3. const char * hello_from_rust(const char *name); 
  4. #endif 

還要變更 C 擴充檔案:

 
  1. PHP_FUNCTION(confirm_hello_from_rust_compiled) 
  2. char *arg = NULL; 
  3. int arg_len, len; 
  4. char *strg; 
  5.  
  6. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &arg, &arg_len) == FAILURE) { 
  7. return; 
  8.  
  9. char *str; 
  10. str = hello_from_rust("Jared (from PHP!!)!"); 
  11. printf("%s/n", str); 
  12.  
  13. len = spprintf(&strg, 0, "Congratulations! You have successfully modified ext/%.78s/config.m4. Module %.78s is now compiled into PHP.", "hello_from_rust", arg); 
  14. RETURN_STRINGL(strg, len, 0); 

無用的微基準

那麼為什麼你還要這樣做?我還真的沒有在現實世界裡使用過這個。但是我真的認為斐波那契序列演算法就是一個好的例子來說明一個PHP拓展如何很基本。通常是直截了當(在Ruby中):

 
  1. def fib(at) do 
  2. if (at == 1  at == 0) 
  3. return at 
  4. else 
  5. return fib(at - 1) + fib(at - 2) 
  6. end 
  7. end 

而且可以通過不使用遞迴來改善這不好的效能:

 
  1. def fib(at) do 
  2. if (at == 1  at == 0) 
  3. return at 
  4. elsif (val = @cache[at]).present? 
  5. return val 
  6. end 
  7.  
  8. total = 1 
  9. parent = 1 
  10. gp = 1 
  11.  
  12. (1..at).each do i 
  13. total = parent + gp 
  14. gp = parent 
  15. parent = total 
  16. end 
  17.  
  18. return total 
  19. end 

那麼我們圍繞它來寫兩個例子,一個在PHP中,一個在Rust中。看看哪個更快。下面是PHP版:

 
  1. def fib(at) do 
  2. if (at == 1  at == 0) 
  3. return at 
  4. elsif (val = @cache[at]).present? 
  5. return val 
  6. end 
  7.  
  8. total = 1 
  9. parent = 1 
  10. gp = 1 
  11.  
  12. (1..at).each do i 
  13. total = parent + gp 
  14. gp = parent 
  15. parent = total 
  16. end 
  17.  
  18. return total 
  19. end 
  20.  
  21. 這是它的運行結果: 
  22.  
  23. $ time php php_fib.php 
  24.  
  25. real 0m2.046s 
  26. user 0m1.823s 
  27. sys 0m0.207s 
  28.  
  29. 現在我們來做Rust版。下面是庫資源: 
  30.  
  31. #![crate_type = "staticlib"] 
  32.  
  33. fn fib(at: usize) -> usize { 
  34. if at == 0 { 
  35. return 0; 
  36. } else if at == 1 { 
  37. return 1; 
  38.  
  39. let mut total = 1; 
  40. let mut parent = 1; 
  41. let mut gp = 0; 
  42. for _ in 1 .. at { 
  43. total = parent + gp; 
  44. gp = parent; 
  45. parent = total; 
  46.  
  47. return total; 
  48.  
  49. #[no_mangle] 
  50. pub extern "C" fn rust_fib(at: usize) -> usize { 
  51. fib(at) 
  52.  
  53. 注意,我編譯的庫rustc – O rust_lib.rs使編譯器最佳化(因為我們是這裡的標準)。這裡是C擴充源(相關摘錄): 
  54.  
  55. PHP_FUNCTION(confirm_rust_fib_compiled) 
  56. long number; 
  57.  
  58. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &number) == FAILURE) { 
  59. return; 
  60.  
  61. RETURN_LONG(rust_fib(number)); 

運行PHP指令碼:

 
  1. <?php 
  2. $br = (php_sapi_name() == "cli")? "":"<br>"; 
  3.  
  4. if(!extension_loaded('rust_fib')) { 
  5. dl('rust_fib.' . PHP_SHLIB_SUFFIX); 
  6.  
  7. for ($i = 0; $i < 100000; $i ++) { 
  8. confirm_rust_fib_compiled(92); 
  9. ?> 
  10.  
  11. 這就是它的運行結果: 
  12.  
  13. $ time php rust_fib.php 
  14.  
  15. real 0m0.586s 
  16. user 0m0.342s 
  17. sys 0m0.221s 

你可以看見它比前者快了三倍!完美的Rust微基準!

總結

這裡幾乎沒有得出什麼結論。我不確定在Rust上寫一個PHP的擴充是一個好的想法,但是花費一些時間去研究Rust,PHP和C,這是一個很好的方式。

如果你希望查看所有代碼或者查看更改記錄,可以訪問GitHub Repo。



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.