rust php 扩展,在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”。

// 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

#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编译器可以提供出来。

经运行下面的代码我们可以得到一个二进制的文件: