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 <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
新聞熱點
疑難解答