在PHP程序中使用Rust扩展的方法,php程序rust扩展
在PHP程序中使用Rust扩展的方法,php程序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 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
我从C(或其它!)中调用的Rust库拆分它。这有一个接下来会怎样的很好的解释。
编译它会得到.a的一个文件,libhello_from_rust.a。这是一个静态的库,包含它自己所有的依赖关系,而且我们在编译一个C程序的时候链接它,这让我们能做后续的事情。注意:在我们编译后会得到如下输出:
1 2 3 4 5 |
|
这就是Rust编译器在我们不使用这个依赖的时候所告诉我们需要链接什么。
从C中调用Rust
既然我们有了一个库,不得不做两件事来保证它从C中可调用。首先,我们需要为它创建一个C的头文件,hello_from_rust.h。然后在我们编译的时候链接到它。
下面是头文件:
1 2 3 4 5 6 7 |
|
这是一个相当基础的头文件,仅仅为了一个简单的函数提供签名/定义。接着我们需要写一个C程序并使用它。
1 2 3 4 5 6 7 8 |
|
我们通过运行一下代码来编译它:
1 |
|
注意在末尾的-lSystem -lpthread -lc -lm告诉gcc不要链接那些“本地的古董”,为了当编译我们的Rust库时Rust编译器可以提供出来。
经运行下面的代码我们可以得到一个二进制的文件:
1 2 |
|
漂亮!我们刚才从C中调用了Rust库。现在我们需要理解Rust库是如何进入一个PHP扩展的。
从 php 中调用 c
该部分花了我一些时间来弄明白,在这个世界上,该文档在 php 扩展中并不是最好的。最好的部分是来自绑定一个脚本 ext_skel 的 php 源(大多数代表“扩展骨架”)即生成大多数你需要的样板代码。 你可以通过下载来开始,和未配额的 php 源,把代码写进 php 目录并且运行:
1 2 |
|
这将生成需要创建 php 扩展的基本骨架。现在,移动你处处想局部地保持你的扩展的文件夹。并且移动你的
- .rust 源
- .rust库
- .c header
进入同一个目录。因此,现在你应该看看像这样的一个目录:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
一个目录,11个文件
你可以在 php docs 在上面看到关于这些文件很好的描述。建立一个扩展的文件。我们将通过编辑 config.m4 来开始吧。
不解释,下面就是我的成果:
1 2 3 4 5 6 7 8 9 10 |
|
正如我所理解的那样,这些是基本的宏命令。但是有关这些宏命令的文档是相当糟糕的(比如: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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
注意:我添加了hello_from_rust("Jared (fromPHP!!)!");。
现在,我们可以试着建立我们的扩展:
1 2 3 |
|
就是它,生成我们的元配置,运行生成的配置命令,然后安装该扩展。安装时,我必须亲自使用sudo,因为我的用户并不拥有安装目录的 php 扩展。
现在,我们可以运行它啦!
1 2 3 4 5 6 7 |
|
还不错,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 头文件:
1 2 3 4 5 6 |
|
还要变更 C 扩展文件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
无用的微基准
那么为什么你还要这样做?我还真的没有在现实世界里使用过这个。但是我真的认为斐波那契序列算法就是一个好的例子来说明一个PHP拓展如何很基本。通常是直截了当(在Ruby中):
1 2 3 4 5 6 7 |
|
而且可以通过不使用递归来改善这不好的性能:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
那么我们围绕它来写两个例子,一个在PHP中,一个在Rust中。看看哪个更快。下面是PHP版:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
这是它的运行结果:
1 2 3 4 5 |
|
现在我们来做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扩展源(相关摘录):
1 2 3 4 5 6 7 8 9 10 |
|
运行PHP脚本:
1 2 3 4 5 6 7 8 9 10 11 |
|
这就是它的运行结果:
1 2 3 4 5 |
|
你可以看见它比前者快了三倍!完美的Rust微基准!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics





JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.

In PHP, you can effectively prevent CSRF attacks by using unpredictable tokens. Specific methods include: 1. Generate and embed CSRF tokens in the form; 2. Verify the validity of the token when processing the request.

Use most text editors to open XML files; if you need a more intuitive tree display, you can use an XML editor, such as Oxygen XML Editor or XMLSpy; if you process XML data in a program, you need to use a programming language (such as Python) and XML libraries (such as xml.etree.ElementTree) to parse.
