首页
学习
活动
专区
工具
TVP
发布

PHP FFI 允许在 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  编译:开源中国

  • 发表于:
  • 原文链接https://www.oschina.net/news/95375/php-ffi-support-c-in-php-script
  • 如有侵权,请联系 cloudcommunity@tencent.com 删除。

扫码

添加站长 进交流群

领取专属 10元无门槛券

私享最新 技术干货

扫码加入开发者社群
领券