当前位置: 首页 > 编程文章 >

在PHP中通过C扩展调用Rust库的完整指南

在PHP中通过C扩展调用Rust库的完整指南

作者:沈禾时间:2026-05-11 12:26:15浏览:513

本文详细演示了如何在PHP中通过C扩展调用Rust编写的静态库。流程包括使用Rust FFI生成.a静态文件、创建对应的C头文件,并利用ext_skel工具构建PHP扩展骨架。重点讲解了config.m4中的宏配置以链接Rust依赖,以及处理字符串传递时的段错误问题。最终通过斐波那契数列算法的微基准测试,展示了Rust实现相比纯PHP代码约三倍的执行速度提升。

本文目录展开

在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 微基准!

上一篇
PHP中foreach()用法详解与示例

PHP 4引入的foreach结构是遍历数组的简便方法,仅支持数组类型。它提供两种语法格式:第一种将当前单元的值赋给变量并移动指针;第二种同时获取键名和值。本文通过一维及二维数组实例,详细解析了foreach在获取元素值和索引时的具体应用及注意事项。

下一篇
PHP 5.3 异常处理新特性与最佳实践

本文探讨 PHP 5.3 中基于异常处理的两个关键新特性:嵌套异常(Nested Exceptions)和 SPL 新增的核心异常类型。通过引入 getPrevious() 方法,开发者可以保留原始异常上下文,实现异常的链式捕获。同时,SPL 扩展提供了 LogicException 和 RuntimeException 等标准化子类,帮助区分逻辑错误与运行时错误,提升代码的可维护性与类型安全性。

相关文章

更多
PHP Memcached 高级缓存配置图文教程

Memcached 作为高性能分布式内存对象缓存系统,能有效缓解数据库压力。本文详细讲解在 Windows 环境下安装 Memcached 服务、通过 Telnet 验证连接,以及在 PHP 中配置 php_memcache.dll 扩展并启用缓存功能的完整步骤。

2025.12.12 981
PHP通过PECL方式安装扩展的完整流程

本文介绍使用PECL工具在Linux环境下快速安装PHP扩展的方法。以Swoole为例,演示了从环境检查、扩展搜索到自动编译安装的步骤。相比phpize手动编译,PECL方式能简化配置过程,但仍需将生成的.so文件路径添加至php.ini并重启服务方可生效。

2026.08.23 951
PHP操作Memcache实例:原理、配置与Session存储

本文介绍PHP环境下Memcache的操作机制及其与Redis的区别。Memcache将数据直接保存在内存中,重启服务或机器会导致数据丢失,并采用LRU算法管理缓存淘汰。通过加载php_memcache.dll扩展或使用Socket客户端,PHP可实现对字符串、数组等数据的存取。此外,文章详细说明了如何将PHP Session数据存储至Memcache,包括通过ini_set函数动态修改配置的方法,以及保存对象时需注意类定义的问题。

2026.07.25 935
使用Zookeeper分布式部署PHP应用程序

ZooKeeper是用于分布式协作的开源服务,提供同步、配置维护等功能。本文介绍如何在PHP环境中通过PECL或GitHub安装ZooKeeper扩展,并演示如何配置CLI环境及启动服务。通过示例脚本展示Watcher机制实现数据变更通知,以及利用EPHEMERAL和SEQUENCE标志构建简单的Leader选举逻辑,帮助开发者快速上手分布式应用开发。

2026.07.14 912
解决PHP扩展安装后重启不生效问题

在LNMP环境中配置PHP扩展时,常遇到编译安装并修改php.ini后,重启php-fpm服务扩展仍未加载的问题。这通常是因为php-fpm启动时未正确指定配置文件路径,导致读取了错误的php.ini或默认配置。解决方法是显式指定php.ini文件路径来启动php-fpm服务,确保其加载正确的扩展配置。若仍无效,需检查php.ini放置路径是否正确。

2025.09.14 877
CentOS 6.3下安装PHP xcache扩展模块笔记

本文记录了在 CentOS 6.3 环境下为 Apache 2.4.4 和 PHP 5.4.13 安装 xcache-3.0.1 缓存扩展的完整流程。主要步骤包括下载源码、使用 phpize 准备编译环境、配置并安装共享扩展模块,以及修改 php.ini 加载 xcache.so 并重启服务。最后通过创建 info.php 页面验证模块是否成功加载。

2025.09.18 868

专题推荐

更多
PHP 类与对象定义及继承

先看类声明、对象实例与属性访问。理解对象的创建和销毁后,再读继承、方法重载和关键字对照。已有代码遇到继承行为差异时,可进一步查看 final 方法与反射实例。

PHP 定时任务配置与运行

先确定任务运行间隔以及是否允许重叠。固定时间触发先看 Cron 案例,框架内和常驻服务再读对应示例。

Yii2 队列配置与常驻运行

先用一个最小任务跑通入队和消费,再检查 Web 与 Console 是否加载了相同的队列配置。确认命令能手动运行后再配置 Supervisor,最后验证进程重启时的处理情况。

PHP Session 过期时间设置方法

浏览器关闭、服务端回收和业务规定的闲置超时,可能在不同时间发生。对照配置项与应用层时间戳的做法,检查会话何时仍可读、何时应要求重新登录。

PHP URL 编码和解码方法

URL 路径片段和查询参数对空格的处理方式不同。先比较 urlencode 与 rawurlencode,再沿解码过程核对中文、加号和百分号,检查地址是否被重复编码或提前解码。

在线工具箱

更多
键码查询
键码查询

按下键盘按键时查看浏览器记录的键名和事件信息。

.env 配置检查
.env 配置检查

本地检查 .env 键值语法、引号、重复键及空值,预览解析结果,辅助排查 PHP 和 Laravel 环境配置。

进制转换
进制转换

转换二进制、十进制、十六进制等数值表示,辅助程序调试与进制学习。

HTML 标签安全清理
HTML 标签安全清理

清理 HTML 片段中的标签或危险内容,辅助整理待展示的文本。

文件 Base64 转换
文件 Base64 转换

把文件转为 Base64 文本,也可将编码内容还原为文件,方便接口传输与调试。