PHP FFI 允许在 PHP 脚本中嵌入 C 代码

新闻 后端
Zend 的 Dmitry Stogov 通过允许 PHP 执行嵌入式 C 代码扩展了 PHP 的领域。 这将允许完全访问本地 C 函数,变量以及数据结构。

 Zend 的 Dmitry Stogov 通过允许 PHP 执行嵌入式 C 代码扩展了 PHP 的领域。 这将允许完全访问本地 C 函数,变量以及数据结构。

[[226718]]

解决方案 PHP FFI 作为实验性扩展提供,但要求 PHP 7.3 的开发版本。 该解决方案还不能用于生产,但它构建在坚实的基础之上,使用 FFI(外部函数接口)库 libffi,允许高级语言生成代码。

输入:

  1. <?php$libc = new FFI(" 
  2.     int printf(const char *format, ...); 
  3.     char * getenv(const char *); 
  4.     unsigned int time(unsigned int *); 
  5.  
  6.     typedef unsigned int time_t; 
  7.     typedef unsigned int suseconds_t; 
  8.  
  9.     struct timeval { 
  10.         time_t      tv_sec; 
  11.         suseconds_t tv_usec; 
  12.     }; 
  13.  
  14.     struct timezone { 
  15.         int tz_minuteswest; 
  16.         int tz_dsttime; 
  17.     }; 
  18.  
  19.     int gettimeofday(struct timeval *tv, struct timezone *tz);     
  20. ", "libc.so.6");$libc->printf("Hello World from %s!\n", "PHP"); 
  21. var_dump($libc->getenv("PATH")); 
  22. var_dump($libc->time(null));$tv = $libc->new("struct timeval");$tz = $libc->new("struct timezone");$libc->gettimeofday($tv$tz); 
  23. var_dump($tv->tv_sec, $tv->tv_usec, $tz);?> 

将输出:

  1. Hello World from PHP! 
  2. 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) 
  3. int(1523617815) 
  4. int(977765) 
  5. object(CData)#3 (2) { 
  6.   ["tz_minuteswest"]=> 
  7.   int(-180) 
  8.   ["tz_dsttime"]=> 
  9.   int(0) 

FFI 目前的数据结构访问还比较缓慢,比访问原始 PHP 数组和对象的速度慢大约 4 倍。现阶段的速度虽然不太乐观,但还是可以帮助节省内存和资金的。

随着 PHP FFI 后续的不断优化,性能还会不断提升。

责任编辑:张燕妮 来源: react-etc.net
相关推荐

2009-03-23 13:08:07

PHP扩展PHPJavascript

2009-12-08 14:20:30

PHP CLI脚本

2009-12-02 19:51:54

PHP Switch语

2011-07-12 17:11:13

PHPSHELL

2011-06-15 16:58:26

PHP

2009-02-27 16:57:51

AJAX判断请求

2009-11-18 13:52:30

PHP shell脚本

2011-02-24 09:41:25

PHP代码

2011-06-15 15:16:54

Session

2009-11-30 16:24:24

PHP脚本

2017-07-27 14:21:40

phpPHP源码分析hashtable

2015-07-02 14:38:44

2022-03-07 10:02:00

PHP社区PHP 贡献者开源项目

2011-03-28 14:35:39

2010-07-11 00:24:50

EclipsePHPPDT

2021-01-22 15:18:21

UbuntuLinuxApache

2009-11-25 10:52:22

PHP函数contin

2010-03-05 10:31:24

Ubuntu PHP

2009-11-16 16:17:45

PHP数组排序

2013-03-25 11:51:42

php漏洞代码审计php
点赞
收藏

51CTO技术栈公众号