使用 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”。


  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。

以上是小编为您精心准备的的内容,在的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索php
, 文件
, return
, 运行
, 一个
, Rust
运行hello
php yar 扩展安装使用、php 扩展使用opencv、php redis 扩展使用、phpkafka扩展使用、php mongodb 扩展使用,以便于您获取更多的相关知识。

时间: 2024-09-17 03:42:20

使用 Rust 创建 PHP 扩展的相关文章

如何使用C创建php扩展

使用C创建php扩展 优点: 1.提高运行效率. 2.降低php复杂度,可以直接调用扩展方法实现功能. 3.方便与第三方库交互. 缺点: 1.开发比php复杂. 2.可维护性降低. 3.开发周期变长.php开发,发现问题后,只要修复问题,即可见到效果.如果使用扩展,修复后需要重新编译,重启服务,才能见到效果. 首先,假定需要实现一个方法:将url字符串转换成超链接. php实现方法: <?php function strtolink($url, $name='', $openwin=0){ $n

Mac OS X与Windows 8双启动环境中创建Windows扩展分区

用了四年多的Thinkpad突然坏了,咬了咬牙,买了台MacBook,使用下来的感 受是帅呆了,不想回到Windows.但Mac下没有Visual Studio的替代品,只能再 装一个Windows 8. 借助Boot Camp安装了Windows 8,但当时只为 Windows 8分了一个区.后来想拉出一个分区出来专门放数据,于是在Windows 8 的"磁盘管理"中收缩(Shrink)C盘,拉出了一部分空间.接着创建分区时, 出现如下错误: The operation you se

三种在Linux上创建或扩展交换分区的简单方法

用户可以在任何 Linux 操作系统的安装过程中或者是其它必要的时候创建交换空间.如果你在安装 Linux 的时候忘记了创建或是你想要再增加交换分区的空间,你随时都可以再创建或增加. 有时候在你安装后摇升级 RAM 的时候需要增加一点交换分区的空间,比如你要将你的系统的 RAM 从 1GB 升级到 2GB 你,那么你就不得不将你的交换分区空间也升级一下(从 2GB 到 4GB),这是因为它使用的容量是物理 RAM 的双倍容量.(LCTT 译注:其实这里是个误区,交换分区不一定非得是双倍的物理内存

怎么样创建一个扩展控件程序?

问题描述 本人一菜鸟正在学习控件使用技术.想咨询一下各位,如何创建一个扩展控件程序,我想将我自己写的扩展控件添加到工具栏中使用.我看一个教程说是"新建项目的时候添加一个类库"对吗?请各出具体操作方法的步骤,当然越简单越好吧,谢谢! 解决方案 解决方案二:1.可以用userControl2.写一个类,继承自系统控件就是.解决方案三:up解决方案四:说的有点抽象...解决方案五:楼主是想做VS插件解决方案六:http://download.csdn.net/detail/yanele/39

20.1. Extension Example 创建一个扩展

下面我们开始分部讲解,首先创建一个扩展. 编辑的config.m4 去掉上面三行前的dnl,dnl表示注释 执行phpize 创建ini文件 确认扩展看装成功 创建php测试程序 输出结果 原文出处:Netkiller 系列 手札 本文作者:陈景峯 转载请与作者联系,同时请务必标明文章原始出处和作者信息及本声明.

NET Framework 用C#创建SHELL扩展

创建 一.前言<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" /> .NET平台是微软公司推出的作为未来软件运行和开发的环境,C#是微软力荐的在.NET平台下开发应用软件的首选语言.本文将讨论在.NET环境下如何使用C#语言开发Windows Shell扩展问题.如今Windows家族已发展到XP世代了,想必每个程序员都对Shell Extension不会感到陌生吧,在这里我

使用jQuery(中级),第1部分:使用插件创建和扩展jQuery函数

简介 自我发表了有关 jQuery JavaScript 库的第一个系列文章的这六个月来,在 jQuery 领域发生了很多事情.对我们这些 jQuery 的信徒而言,最令人激动的莫过于 Microsoft 已经选择在其 Visual Studio 套件中使用 jQuery,并已经决定将 jQuery 作为目前该套件所包含的惟一的 JavaScript 库.这显示了对 jQuery 的极大支持,帮助巩固了 jQuery 作为适用于 Web 应用程序的领先 JavaScript 库的地位.jQuer

创建并扩展Apache Wicket Web应用

简介 Apache Wicket是一个功能强大.基于组件的轻量级Web应用框架,能将展现和业务逻辑很好地分离开来.你能用它创建易于测试.调试和支持的高质量Web 2.0应用.假设其他团队交付了一个基于Wicket的应用,你必须扩展该应用,但又不能修改他们的代码:或者你必须要交付一个模块化的Web应用,能让其他团队很容易地扩展和定制.本文介绍的正是如何在不引入多余源代码.标记和配置的情况下解决此问题.我们用maven-war-plugin合并项目,用wicketstuff-annotations动

技巧/诀窍:用.NET 3.5创建ToJSON()扩展方法

扩展方法让开发者可以向已有的 CLR 类型的公共契约中添加新的方法,而不 需要子类化或重新编译原有的类型.通过这种做法,可以使很多有用的应用场景 成为可能(包括 LINQ).同时,扩展方法也可以用来非常方便地向代码中添加 "语法糖". 过去几个月,我一直在准备一些很酷的扩展方法的清单,并计划在有空的时 候实现它们(不确定何时...但至少我还能从这些想法中获得乐趣).在上述清 单中有两个扩展方法的应用场景,分别是用于为任意 .NET 对象自动生成JSON (JavaScript Obje