>  기사  >  백엔드 개발  >  Rust를 사용하여 PHP 확장 만들기

Rust를 사용하여 PHP 확장 만들기

伊谢尔伦
伊谢尔伦원래의
2016-12-02 09:41:421514검색

지난 10월 Etsy 동료들과 저는 PHP와 같은 해석 언어용 확장 기능을 작성하는 방법에 대해 논의했습니다. 현재 Ruby나 Python의 상황은 PHP보다 쉬워야 합니다. 우리는 성공적인 확장 기능을 작성하는 데 장애가 되는 점은 일반적으로 C로 작성해야 하지만 C에 능숙하지 않으면 그러한 자신감을 갖기가 어렵다는 점에 대해 이야기했습니다.

그 이후로 나는 Rust로 하나 작성해보고 싶다는 생각이 들었고, 지난 며칠 동안 그것을 시도해 왔습니다. 드디어 오늘 아침에 실행하게 되었습니다.

C 또는 PHP의 Rust

나의 기본적인 시작점은 컴파일 가능한 Rust 코드를 라이브러리에 작성하고 이를 위한 C 헤더 파일을 작성하는 것입니다. C에서는 PHP를 호출하여 만드는 것입니다. 확장. 쉽지는 않지만 재미있습니다.

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에서 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 <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은 gcc에 해당 "로컬 골동품"을 링크하지 말라고 지시합니다. , Rust 컴파일러가 Rust 라이브러리를 컴파일할 때 이를 제공하도록 하기 위한 것입니다.

다음 코드를 실행하면 바이너리 파일을 얻을 수 있습니다.

$ ./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 헤더

를 같은 디렉터리로 이동하세요. 이제 다음과 같은 디렉터리를 살펴봐야 합니다:

.
├── 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
└── 테스트
└── 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으로 문의하세요.