PHP FFI 允許在 PHP 腳本中嵌入 C 代碼
作者:開源中國編譯
Zend 的 Dmitry Stogov 通過允許 PHP 執行嵌入式 C 代碼擴展了 PHP 的領域。 這將允許完全訪問本地 C 函數,變量以及數據結構。
Zend 的 Dmitry Stogov 通過允許 PHP 執行嵌入式 C 代碼擴展了 PHP 的領域。 這將允許完全訪問本地 C 函數,變量以及數據結構。
解決方案 PHP FFI 作為實驗性擴展提供,但要求 PHP 7.3 的開發版本。 該解決方案還不能用于生產,但它構建在堅實的基礎之上,使用 FFI(外部函數接口)庫 libffi,允許高級語言生成代碼。
輸入:
- <?php$libc = new FFI("
- int printf(const char *format, ...);
- char * getenv(const char *);
- unsigned int time(unsigned int *);
- typedef unsigned int time_t;
- typedef unsigned int suseconds_t;
- struct timeval {
- time_t tv_sec;
- suseconds_t tv_usec;
- };
- struct timezone {
- int tz_minuteswest;
- int tz_dsttime;
- };
- int gettimeofday(struct timeval *tv, struct timezone *tz);
- ", "libc.so.6");$libc->printf("Hello World from %s!\n", "PHP");
- var_dump($libc->getenv("PATH"));
- var_dump($libc->time(null));$tv = $libc->new("struct timeval");$tz = $libc->new("struct timezone");$libc->gettimeofday($tv, $tz);
- var_dump($tv->tv_sec, $tv->tv_usec, $tz);?>
將輸出:
- Hello World from PHP!
- string(135) "/usr/lib64/qt-3.3/bin:/usr/lib64/ccache:/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/home/dmitry/.local/bin:/home/dmitry/bin"int(1523617815)
- int(1523617815)
- int(977765)
- object(CData)#3 (2) {
- ["tz_minuteswest"]=>
- int(-180)
- ["tz_dsttime"]=>
- int(0)
- }
FFI 目前的數據結構訪問還比較緩慢,比訪問原始 PHP 數組和對象的速度慢大約 4 倍。現階段的速度雖然不太樂觀,但還是可以幫助節省內存和資金的。
隨著 PHP FFI 后續的不斷優化,性能還會不斷提升。
責任編輯:張燕妮
來源:
react-etc.net