使用 rust 建立 php 擴充
去年十月,我和 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」。
// 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庫拆分它。這有一個接下來會怎樣的很好的解釋。
編譯它會得到.a的一個文件,libhello_from_rust.a。這是一個靜態的函式庫,包含它自己所有的依賴關係,而且我們在編譯一個C程式的時候連結它,這讓我們能做後續的事情。注意:在我們編譯後會得到如下輸出:
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編譯器在我們不使用這個依賴的時候所告訴我們需要連結什麼。
從C中調用Rust
既然我們有了一個庫,不得不做兩件事來保證它從C中可調用。首先,我們需要為它建立一個C的頭文件,hello_from_rust.h。然後在我們編譯的時候連結到它。
下面是頭文件:
// hello_from_rust.h #ifndef __HELLO #define __HELLO void hello_from_rust(const char *name); #endif
這是一個相當基礎的頭文件,僅僅為了一個簡單的函數提供簽名/定義。接著我們需要寫一個C程式並使用它。
// hello.c #include <stdio.h> #include <stdlib.h> #include "hello_from_rust.h" int main(int argc, char *argv[]) { 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編譯器可以提供出來。
經運行下面的程式碼我們可以得到一個二進位的檔案:
$ ./hello_c Hello from Rust, Jared!
漂亮!我們剛才從C中呼叫了Rust函式庫。現在我們要理解Rust函式庫是如何進入一個PHP擴充的。
從 php 中調用 c
該部分花了我一些時間來弄清楚,在這個世界上,該文檔在 php 擴展中並不是最好的。最好的部分是來自綁定一個腳本 ext_skel 的 php 來源(大多數代表「擴展骨架」)即產生大多數你需要的樣板程式碼。為了讓程式碼運行,我十分努力地學習 php 文檔,「擴展骨骼」。
你可以透過下載來開始,和未配額的php 來源,把程式碼寫進php 目錄並且運作:
$ cd ext/
$ ./ext_skel –extname=hello_from_rust
這將需要創建需要創建的擴充基本骨架。現在,移動你處處想局部地保持你的擴充的資料夾。並且移動你的
.rust 源
.rust庫
.c header
進入同一個目錄。因此,現在你應該看看像這樣的目錄:
.
├── CREDITS
├── EXPERIMENTAL
├── config.m4
├── config.w32
├⎜✔⠜_ config.w32
✔ ─ hello_from_rust.h
├── hello_from_rust.php
├── hello_from_rust.rs
├── libhello_from_rust.a
testtest phpt
一個目錄,11個文件
你可以在php docs 在上面看到關於這些文件很好的描述。建立一個擴充的檔案。我們將透過編輯 config.m4 來開始吧。
不解釋,以下是我的成果:
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脚本中实际地调用库。为此我们得修改自动生成的文件,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!!)!”);。
现在,我们可以试着建立我们的扩展:
$ phpize
$ ./configure
$ sudo make install
就是它,生成我们的元配置,运行生成的配置命令,然后安装该扩展。安装时,我必须亲自使用sudo,因为我的用户并不拥有安装目录的 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 库,开始打印我们的字符串。那很有趣!但是……那段错误的结局发生了什么?
正如我所提到的,这里是使用了 Rust 相关的 println! 宏,但是我没有对它做进一步的调试。如果我们从我们的 Rust 库中删除并返回一个 char* 替代,段错误就会消失。
这里是 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 扩展文件:
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拓展如何很基本。通常是直截了当(在Ruby中):
def fib(at) do if (at == 1 || at == 0) return at else return fib(at - 1) + fib(at - 2) end end
而且可以通过不使用递归来改善这不好的性能:
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版:
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
这是它的运行结果:
$ time php php_fib.php real 0m2.046s user 0m1.823s sys 0m0.207s
现在我们来做Rust版。下面是库资源:
#![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) }
注意,我编译的库rustc – O rust_lib.rs使编译器优化(因为我们是这里的标准)。这里是C扩展源(相关摘录):
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 $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); } ?>
这就是它的运行结果:
$ time php rust_fib.php real 0m0.586s user 0m0.342s sys 0m0.221s
你可以看见它比前者快了三倍!完美的Rust微基准!
总结
这里几乎没有得出什么结论。我不确定在Rust上写一个PHP的扩展是一个好的想法,但是花费一些时间去研究Rust,PHP和C,这是一个很好的方式。

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

JWT是一種基於JSON的開放標準,用於在各方之間安全地傳輸信息,主要用於身份驗證和信息交換。 1.JWT由Header、Payload和Signature三部分組成。 2.JWT的工作原理包括生成JWT、驗證JWT和解析Payload三個步驟。 3.在PHP中使用JWT進行身份驗證時,可以生成和驗證JWT,並在高級用法中包含用戶角色和權限信息。 4.常見錯誤包括簽名驗證失敗、令牌過期和Payload過大,調試技巧包括使用調試工具和日誌記錄。 5.性能優化和最佳實踐包括使用合適的簽名算法、合理設置有效期、

字符串是由字符組成的序列,包括字母、數字和符號。本教程將學習如何使用不同的方法在PHP中計算給定字符串中元音的數量。英語中的元音是a、e、i、o、u,它們可以是大寫或小寫。 什麼是元音? 元音是代表特定語音的字母字符。英語中共有五個元音,包括大寫和小寫: a, e, i, o, u 示例 1 輸入:字符串 = "Tutorialspoint" 輸出:6 解釋 字符串 "Tutorialspoint" 中的元音是 u、o、i、a、o、i。總共有 6 個元

靜態綁定(static::)在PHP中實現晚期靜態綁定(LSB),允許在靜態上下文中引用調用類而非定義類。 1)解析過程在運行時進行,2)在繼承關係中向上查找調用類,3)可能帶來性能開銷。

PHP的魔法方法有哪些? PHP的魔法方法包括:1.\_\_construct,用於初始化對象;2.\_\_destruct,用於清理資源;3.\_\_call,處理不存在的方法調用;4.\_\_get,實現動態屬性訪問;5.\_\_set,實現動態屬性設置。這些方法在特定情況下自動調用,提升代碼的靈活性和效率。

PHP和Python各有優勢,選擇依據項目需求。 1.PHP適合web開發,尤其快速開發和維護網站。 2.Python適用於數據科學、機器學習和人工智能,語法簡潔,適合初學者。

PHP在電子商務、內容管理系統和API開發中廣泛應用。 1)電子商務:用於購物車功能和支付處理。 2)內容管理系統:用於動態內容生成和用戶管理。 3)API開發:用於RESTfulAPI開發和API安全性。通過性能優化和最佳實踐,PHP應用的效率和可維護性得以提升。

PHP是一種廣泛應用於服務器端的腳本語言,特別適合web開發。 1.PHP可以嵌入HTML,處理HTTP請求和響應,支持多種數據庫。 2.PHP用於生成動態網頁內容,處理表單數據,訪問數據庫等,具有強大的社區支持和開源資源。 3.PHP是解釋型語言,執行過程包括詞法分析、語法分析、編譯和執行。 4.PHP可以與MySQL結合用於用戶註冊系統等高級應用。 5.調試PHP時,可使用error_reporting()和var_dump()等函數。 6.優化PHP代碼可通過緩存機制、優化數據庫查詢和使用內置函數。 7

PHP仍然具有活力,其在現代編程領域中依然佔據重要地位。 1)PHP的簡單易學和強大社區支持使其在Web開發中廣泛應用;2)其靈活性和穩定性使其在處理Web表單、數據庫操作和文件處理等方面表現出色;3)PHP不斷進化和優化,適用於初學者和經驗豐富的開發者。
