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 = "html' target='_blank'>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 librarynote: the order and any duplication can be significant on some platforms, and so may need to be preservednote: library: Systemnote: library: pthreadnote: library: cnote: library: m这就是Rust编译器在我们不使用这个依赖的时候所告诉我们需要链接什么。从C中调用Rust既然我们有了一个库,不得不做两件事来保证它从C中可调用。首先,我们需要为它创建一个C的头文件,hello_from_rust.h。然后在我们编译的时候链接到它。下面是头文件:
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)正如我所理解的那样,这些是基本的宏命令。但是有关这些宏命令的文档是相当糟糕的(比如: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.phpFunctions available in the test extension:confirm_hello_from_rust_compiledHello 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 __HELLOconst 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)而且可以通过不使用递归来改善这不好的性能:
def fib(at) do if (at == 1 || at == 0) return at elsif (val = @cache[at]).present return val total = 1 parent = 1 gp = 1 (1..at).each do |i| total = parent + gp gp = parent parent = total return total那么我们围绕它来写两个例子,一个在PHP中,一个在Rust中。看看哪个更快。下面是PHP版:
def fib(at) do if (at == 1 || at == 0) return at elsif (val = @cache[at]).present return val total = 1 parent = 1 gp = 1 (1..at).each do |i| total = parent + gp gp = parent parent = total return total这是它的运行结果: