在PHP中通过C扩展调用Rust库
在PHP程序中使用Rust扩展的方法
核心思路是将Rust代码编译为库,并为其编写C语言头文件,进而基于C语言为PHP开发扩展。尽管步骤并非 trivial,但这一过程极具探索价值。 涉及的关键技术是 Rust FFI(外部函数接口)。
第一步是熟悉 Rust 与 C 交互的 FFI 机制。我编写了一个名为 hello_from_rust 的简单库,该库接收一个指向 C 字符的指针(即字符串),并输出 "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 库进行拆分整理。有关后续步骤的详细解释如下。
编译后会生成 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 调用:首先创建头文件 hello_from_rust.h,然后在编译时链接该库。
头文件内容如下:
// hello_from_rust.h
#ifndef __HELLO
#define __HELLO
void hello_from_rust(const char *name);
#endif
这是一个基础的头文件,仅提供了函数的签名/定义。随后需要编写一个 C 程序并使用它。
// hello.c
#include
#include
#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 扩展文档并非最佳参考。最好的资源来自 PHP 源码中的 ext_skel 脚本(代表“扩展骨架”),它能生成大部分所需的样板代码。你可以下载未配额的 PHP 源码,进入 php 目录并运行:
$ cd ext/
$ ./ext_skel --extname=hello_from_rust
这将生成创建 PHP 扩展所需的基本骨架。现在,将你希望局部保留扩展的文件夹移动过来,并将以下文件移入:
- .rust 源代码
- .rust 库文件
- .c 头文件
放入同一目录。此时目录结构应类似如下:
.
├── 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 文档中找到关于这些文件的详细描述。建立扩展的第一步是编辑 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
据我理解,这些是基本的宏命令。但这些宏的文档相当糟糕(例如,搜索“PHP_ADD_LIBRARY_WITH_PATH”并未找到 PHP 团队撰写的结果)。我偶然发现 PHP_ADD_LIBRARY_PATH 宏出现在有人讨论在 PHP 拓展中链接静态库的旧线程中。评论中推荐的其他宏是在运行 ext_skel 后生成的。
配置设置完成后,需要从 PHP 脚本中实际调用库。为此需修改自动生成的文件 hello_from_rust.c。首先在 include 命令中添加 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 库中删除 println! 并返回 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")? "":"
";
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 微基准!