>  기사  >  백엔드 개발  >  Rust에 대한 PHP 확장

Rust에 대한 PHP 확장

*文
*文원래의
2017-12-26 16:54:582155검색

이 글에서는 주로 PHP 프로그램에서 Rust 확장을 사용하는 방법을 소개합니다. 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에서 호출 가능하도록 두 가지 작업을 수행해야 합니다. 먼저 이를 위한 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 확장에 어떻게 들어가는지 이해해야 합니다.


Call c from php

이 부분을 알아내는 데 시간이 좀 걸렸고 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

내가 이해한 바에 따르면 이는 기본 매크로 명령입니다. 그러나 이러한 매크로에 대한 문서는 매우 열악합니다(예: google "PHP_ADD_LIBRARY_WITH_PATH"는 PHP 팀이 작성한 결과를 표시하지 않습니다). 나는 누군가가 PHP 확장에서 정적 라이브러리를 연결하는 것에 대해 이야기했던 이전 스레드에서 이 PHP_ADD_LIBRARY_PATH 매크로를 발견했습니다. 댓글의 다른 권장 매크로는 ext_skel을 실행한 후에 생성되었습니다.

이제 구성 설정이 완료되었으므로 실제로 PHP 스크립트에서 라이브러리를 호출해야 합니다. 이를 수행하려면 자동으로 생성된 파일인 hello_from_rust.c를 수정해야 합니다. 먼저 hello_from_rust.h 헤더 파일을 include 명령에 추가합니다. 그런 다음 verify_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

그렇습니다. 메타 구성을 생성하고 생성된 구성 명령을 실행한 다음 확장을 설치합니다. 설치할 때 내 사용자가 설치 디렉터리에 대한 PHP 확장자를 소유하지 않았기 때문에 직접 sudo를 사용해야 했습니다.

이제 실행할 수 있습니다!

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

相关推荐:

macOS 中使用 phpize 动态添加 PHP 扩展的错误解决方法

Linux 下 PHP 扩展 cURL 编译安装

PHP 扩展库

위 내용은 Rust에 대한 PHP 확장의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
이전 기사:PHP 소켓 UDP 통신다음 기사:PHP 소켓 UDP 통신