使用 Rust 創(chuàng)建 PHP 擴(kuò)展
從那時(shí)起我便萌生了用Rust寫一個(gè)的想法,過(guò)去的幾天一直在嘗試。今天上午我終于讓它運(yùn)行了。
C或PHP中的Rust
我的基本出發(fā)點(diǎn)就是寫一些可以編譯的Rust代碼到一個(gè)庫(kù)里面,并寫為它一些C的頭文件,在C中為被調(diào)用的PHP做一個(gè)拓展。雖然并不是很簡(jiǎn)單,但是很有趣。
Rust FFI(foreign function interface)
我所做的***件事情就是擺弄Rust與C連接的Rust的外部函數(shù)接口。我曾用簡(jiǎn)單的方法(hello_from_rust)寫過(guò)一個(gè)靈活的庫(kù),伴有單一的聲明(a pointer to a C char, otherwise known as a string),如下是輸入后輸出的“Hello from Rust”。
- // 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(或其它!)中調(diào)用的Rust庫(kù)拆分它。這有一個(gè)接下來(lái)會(huì)怎樣的很好的解釋。
編譯它會(huì)得到.a的一個(gè)文件,libhello_from_rust.a。這是一個(gè)靜態(tài)的庫(kù),包含它自己所有的依賴關(guān)系,而且我們?cè)诰幾g一個(gè)C程序的時(shí)候鏈接它,這讓我們能做后續(xù)的事情。注意:在我們編譯后會(huì)得到如下輸出:
- 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編譯器在我們不使用這個(gè)依賴的時(shí)候所告訴我們需要鏈接什么。
從C中調(diào)用Rust
既然我們有了一個(gè)庫(kù),不得不做兩件事來(lái)保證它從C中可調(diào)用。首先,我們需要為它創(chuàng)建一個(gè)C的頭文件,hello_from_rust.h。然后在我們編譯的時(shí)候鏈接到它。
下面是頭文件:
- 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
這是一個(gè)相當(dāng)基礎(chǔ)的頭文件,僅僅為了一個(gè)簡(jiǎn)單的函數(shù)提供簽名/定義。接著我們需要寫一個(gè)C程序并使用它。
- // hello.c
- #include <stdio.h>
- #include <stdlib.h>
- #include "hello_from_rust.h"
- int main(int argc, char *argv[]) {
- hello_from_rust("Jared!");
- }
我們通過(guò)運(yùn)行一下代碼來(lái)編譯它:
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不要鏈接那些“本地的古董”,為了當(dāng)編譯我們的Rust庫(kù)時(shí)Rust編譯器可以提供出來(lái)。
經(jīng)運(yùn)行下面的代碼我們可以得到一個(gè)二進(jìn)制的文件:
- $ ./hello_c
- Hello from Rust, Jared!
漂亮!我們剛才從C中調(diào)用了Rust庫(kù)。現(xiàn)在我們需要理解Rust庫(kù)是如何進(jìn)入一個(gè)PHP擴(kuò)展的。
從 php 中調(diào)用 c
該部分花了我一些時(shí)間來(lái)弄明白,在這個(gè)世界上,該文檔在 php 擴(kuò)展中并不是***的。***的部分是來(lái)自綁定一個(gè)腳本 ext_skel 的 php 源(大多數(shù)代表“擴(kuò)展骨架”)即生成大多數(shù)你需要的樣板代碼。為了讓代碼運(yùn)行,我十分努力地學(xué)習(xí) php 文檔,“擴(kuò)展骨骼”。
你可以通過(guò)下載來(lái)開(kāi)始,和未配額的 php 源,把代碼寫進(jìn) php 目錄并且運(yùn)行:
- $ cd ext/
- $ ./ext_skel –extname=hello_from_rust
這將生成需要?jiǎng)?chuàng)建 php 擴(kuò)展的基本骨架。現(xiàn)在,移動(dòng)你處處想局部地保持你的擴(kuò)展的文件夾。并且移動(dòng)你的
.rust 源
.rust庫(kù)
.c header
進(jìn)入同一個(gè)目錄。因此,現(xiàn)在你應(yīng)該看看像這樣的一個(gè)目錄:
.
├── 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
一個(gè)目錄,11個(gè)文件
你可以在 php docs 在上面看到關(guān)于這些文件很好的描述。建立一個(gè)擴(kuò)展的文件。我們將通過(guò)編輯 config.m4 來(lái)開(kāi)始吧。
不解釋,下面就是我的成果:
- 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
正如我所理解的那樣,這些是基本的宏命令。但是有關(guān)這些宏命令的文檔是相當(dāng)糟糕的(比如:google”PHP_ADD_LIBRARY_WITH_PATH”并沒(méi)有出現(xiàn)PHP團(tuán)隊(duì)所寫的結(jié)果)。我偶然這個(gè)PHP_ADD_LIBRARY_PATH宏命令在有些人所談?wù)摰脑谝粋€(gè)PHP拓展里鏈接一個(gè)靜態(tài)庫(kù)的先前的線程里。在評(píng)論中其它的推薦使用的宏命令是在我運(yùn)行ext_skel后產(chǎn)生的。
既然我們進(jìn)行了配置設(shè)置,我們需要從PHP腳本中實(shí)際地調(diào)用庫(kù)。為此我們得修改自動(dòng)生成的文件,hello_from_rust.c。首先我們添加hello_from_rust.h頭文件到包含命令中。然后我們要修改confirm_hello_from_rust_compiled的定義方法。
- #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!!)!”);。
現(xiàn)在,我們可以試著建立我們的擴(kuò)展:
- $ phpize
- $ ./configure
- $ sudo make install
就是它,生成我們的元配置,運(yùn)行生成的配置命令,然后安裝該擴(kuò)展。安裝時(shí),我必須親自使用sudo,因?yàn)槲业挠脩舨⒉粨碛邪惭b目錄的 php 擴(kuò)展。
現(xiàn)在,我們可以運(yùn)行它啦!
- $ 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
還不錯(cuò),php 已進(jìn)入我們的 c 擴(kuò)展,看到我們的應(yīng)用方法列表并且調(diào)用。接著,c 擴(kuò)展已進(jìn)入我們的 rust 庫(kù),開(kāi)始打印我們的字符串。那很有趣!但是……那段錯(cuò)誤的結(jié)局發(fā)生了什么?
正如我所提到的,這里是使用了 Rust 相關(guān)的 println! 宏,但是我沒(méi)有對(duì)它做進(jìn)一步的調(diào)試。如果我們從我們的 Rust 庫(kù)中刪除并返回一個(gè) char* 替代,段錯(cuò)誤就會(huì)消失。
這里是 Rust 的代碼:
- #![crate_type = "staticlib"]
- #![feature(libc)]
- extern crate libc;
- use std::ffi::{CStr, CString};
- #[no_mangle]
- pub extern "C" fn hello_from_rust(name: *const libc::c_char) -> *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);
- CString::new(c_name).unwrap().as_ptr()
- }
并變更 C 頭文件:
- #ifndef __HELLO
- #define __HELLO
- const char * hello_from_rust(const char *name);
- #endif
還要變更 C 擴(kuò)展文件:
- 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);
- }
無(wú)用的微基準(zhǔn)
那么為什么你還要這樣做?我還真的沒(méi)有在現(xiàn)實(shí)世界里使用過(guò)這個(gè)。但是我真的認(rèn)為斐波那契序列算法就是一個(gè)好的例子來(lái)說(shuō)明一個(gè)PHP拓展如何很基本。通常是直截了當(dāng)(在Ruby中):
- def fib(at) do
- if (at == 1 || at == 0)
- return at
- else
- return fib(at - 1) + fib(at - 2)
- end
- end
而且可以通過(guò)不使用遞歸來(lái)改善這不好的性能:
- 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
那么我們圍繞它來(lái)寫兩個(gè)例子,一個(gè)在PHP中,一個(gè)在Rust中??纯茨膫€(gè)更快。下面是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
- 這是它的運(yùn)行結(jié)果:
- $ time php php_fib.php
- real 0m2.046s
- user 0m1.823s
- sys 0m0.207s
- 現(xiàn)在我們來(lái)做Rust版。下面是庫(kù)資源:
- #![crate_type = "staticlib"]
- fn fib(at: usize) -> usize {
- if at == 0 {
- return 0;
- } else if at == 1 {
- return 1;
- }
- let mut total = 1;
- let mut parent = 1;
- let mut gp = 0;
- for _ in 1 .. at {
- total = parent + gp;
- gp = parent;
- parent = total;
- }
- return total;
- }
- #[no_mangle]
- pub extern "C" fn rust_fib(at: usize) -> usize {
- fib(at)
- }
- 注意,我編譯的庫(kù)rustc – O rust_lib.rs使編譯器優(yōu)化(因?yàn)槲覀兪沁@里的標(biāo)準(zhǔn))。這里是C擴(kuò)展源(相關(guān)摘錄):
- 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));
- }
運(yùn)行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);
- }
- ?>
- 這就是它的運(yùn)行結(jié)果:
- $ time php rust_fib.php
- real 0m0.586s
- user 0m0.342s
- sys 0m0.221s
你可以看見(jiàn)它比前者快了三倍!***的Rust微基準(zhǔn)!
總結(jié)
這里幾乎沒(méi)有得出什么結(jié)論。我不確定在Rust上寫一個(gè)PHP的擴(kuò)展是一個(gè)好的想法,但是花費(fèi)一些時(shí)間去研究Rust,PHP和C,這是一個(gè)很好的方式。
如果你希望查看所有代碼或者查看更改記錄,可以訪問(wèn)GitHub Repo。