国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > PHP > 正文

在PHP程序中使用Rust擴展的方法

2024-05-04 23:37:14
字體:
來源:轉載
供稿:網友
這篇文章主要介紹了在PHP程序中使用Rust擴展的方法,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”。
 
 

  1. // hello_from_rust.rs 
  2. #![crate_type = "staticlib"] 
  3.   
  4. #![feature(libc)] 
  5. extern crate libc; 
  6. use std::ffi::CStr; 
  7.   
  8. #[no_mangle] 
  9. pub extern "C" fn hello_from_rust(name: *const libc::c_char) { 
  10.  let buf_name = unsafe { CStr::from_ptr(name).to_bytes() }; 
  11.  let str_name = String::from_utf8(buf_name.to_vec()).unwrap(); 
  12.  let c_name = format!("Hello from Rust, {}", str_name); 
  13.  println!("{}", c_name); 
 

我從C(或其它!)中調用的Rust庫拆分它。這有一個接下來會怎樣的很好的解釋。

編譯它會得到.a的一個文件,libhello_from_rust.a。這是一個靜態的庫,包含它自己所有的依賴關系,而且我們在編譯一個C程序的時候鏈接它,這讓我們能做后續的事情。注意:在我們編譯后會得到如下輸出:
 

  1. note: link against the following native artifacts when linking against this static library 
  2. note: the order and any duplication can be significant on some platforms, and so may need to be preserved 
  3. note: library: Systemnote: library: pthread 
  4. note: library: c 
  5. note: library: m 
 

這就是Rust編譯器在我們不使用這個依賴的時候所告訴我們需要鏈接什么。

從C中調用Rust

既然我們有了一個庫,不得不做兩件事來保證它從C中可調用。首先,我們需要為它創建一個C的頭文件,hello_from_rust.h。然后在我們編譯的時候鏈接到它。

下面是頭文件:
 

  1. // hello_from_rust.h 
  2. #ifndef __HELLO 
  3. #define __HELLO 
  4.   
  5. void hello_from_rust(const char *name); 
  6.   
  7. #endif 
 

這是一個相當基礎的頭文件,僅僅為了一個簡單的函數提供簽名/定義。接著我們需要寫一個C程序并使用它。
 

  1. // hello.c 
  2. #include <stdio.h> 
  3. #include <stdlib.h> 
  4. #include "hello_from_rust.h" 
  5.   
  6. int main(int argc, char *argv[]) { 
  7.  hello_from_rust("Jared!"); 
 

我們通過運行一下代碼來編譯它:
 

  1. gcc -Wall -o hello_c hello.c -L /Users/jmcfarland/code/rust/php-hello-rust -lhello_from_rust -lSystem -lpthread -lc -lm 
?
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 囊谦县| 曲麻莱县| 千阳县| 安达市| 晋州市| 上虞市| 巴林左旗| 连州市| 永嘉县| 南投市| 陵川县| 丹东市| 焦作市| 渑池县| 灵台县| 遵义市| 宁蒗| 措美县| 峨眉山市| 中牟县| 临沭县| 眉山市| 鄂尔多斯市| 荥阳市| 临朐县| 天全县| 邳州市| 离岛区| 鄂州市| 土默特右旗| 汝南县| 临城县| 广元市| 和政县| 贵德县| 新龙县| 禄劝| 南京市| 靖远县| 教育| 邹平县|