ホームページ  >  記事  >  バックエンド開発  >  Rustを使用してPHP拡張機能を作成する

Rustを使用してPHP拡張機能を作成する

伊谢尔伦
伊谢尔伦オリジナル
2016-12-02 09:41:421509ブラウズ

昨年 10 月、私は Etsy の同僚と、現時点では PHP よりも Ruby や Python のようなインタープリター型言語の拡張機能を作成する方法について話し合いました。正常な拡張機能を作成する上で障壁となるのは、通常は C で作成する必要があることですが、C が苦手な場合はその自信を持つのが難しいことについて説明しました。

それ以来、Rust で書くというアイデアを思いつき、ここ数日試しています。今朝やっと起動できました。

C または PHP での Rust

私の基本的な開始点は、コンパイル可能な Rust コードをライブラリに書き込み、そのコード用の C ヘッダー ファイルをいくつか書き、呼び出された PHP 用の拡張機能を C で作成することです。簡単ではありませんが、楽しいです。

Rust FFI (外部関数インターフェース)

私が最初にやったことは、Rust を C に接続する Rust の外部関数インターフェースを試してみることでした。私はかつて、単一の宣言 (文字列とも呼ばれる C 文字へのポインター) を持つ単純なメソッド (hello_from_rust) を使用して柔軟なライブラリを作成しました。これは、入力後の「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 ライブラリから分割しました。次に何が起こるのかをわかりやすく説明します。

それをコンパイルすると、.a、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 から呼び出せるようにするために 2 つのことを行う必要があります。まず、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 <stdio.h>
#include <stdlib.h>
#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 は、Rust コンパイラが Rust ライブラリをコンパイルするときにリンクできるように、これらの「ローカル アンティーク」に対してリンクしないよう gcc に指示することに注意してください。それを提供してください。

次のコードを実行すると、バイナリ ファイルを取得できます:

$ ./hello_c
Hello from Rust, Jared!

美しい! C から Rust ライブラリを呼び出したところです。次に、Rust ライブラリがどのように PHP 拡張機能に組み込まれるかを理解する必要があります。

php から c を呼び出す

この部分を理解するのに時間がかかり、ドキュメントは php 拡張機能に関しては世界で最も優れたものではありません。最良の部分は、php ソースが、必要な定型コードのほとんどを生成するスクリプト ext_skel (主に「拡張スケルトン」の略) をバンドルして得られることです。コードを実行するために、私は PHP ドキュメント「Extended Bones」を一生懸命勉強しました。

無修正の php ソースをダウンロードし、php ディレクトリにコードを書き込んで実行することで開始できます:

$ cd ext/
$ ./ext_skel –extname=hello_from_rust

これにより、php の作成に必要なコードが生成されます拡張 基本スケルトン。次に、拡張機能をローカルに保持したい場所にフォルダーを移動します。そして、

.rust ソース

.rust ライブラリ

.c ヘッダー

を同じディレクトリに移動します。したがって、次のようなディレクトリを確認する必要があります:

.
til── CREDITS
til── EXPERIMENTAL
til── config.m4
til── config.w32
til── hello_from_rust.c
til── ─ hello_from_rust .h
§── hello_from_rust.php
├── hello_from_rust.rs
§── libhello_from_rust.a
§── php_hello_from_rust.h
└── テスト
└── 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

正如我所理解的那样,这些是基本的宏命令。但是有关这些宏命令的文档是相当糟糕的(比如: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.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 库中删除并返回一个 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")? "":"<br>";
if(!extension_loaded(&#39;rust_fib&#39;)) {
    dl(&#39;rust_fib.&#39; . 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微基准!

总结

这里几乎没有得出什么结论。我不确定在Rust上写一个PHP的扩展是一个好的想法,但是花费一些时间去研究Rust,PHP和C,这是一个很好的方式。


声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。