PHP 7.4 将更好地支持使用 C 函数/数据结构

2019-11-15 08:00 By 茹茹 3094 0 3

    即将在下月底发布的 PHP 7.4 将会引入一个有趣的新功能,那就是期待已久的对 FFI(外部函数接口,Foreign Function Interface)的支持。此功能使得开发者可以在原生 PHP 代码中调用 C 定义的函数/变量/数据结构。

    FFI 与预加载功能都将是 PHP 7.4 的重要新功能,FFI 还增强了 PHP FPM systemd 服务、用于 OpenSSL 流的 TLS 1.3 以及许多其他更改。PHP 7.4 的 FFI 甚至可与其他语言的 FFI 实现相媲美。

    使用 PHP FFI 应该可以减少为 C 库/程序接口编写新 PHP 模块的需求,因为现在可以使用外部函数接口来完成了。如果你对 PHP 7.4 FFI 的示例代码感到好奇,负责 Fedora/RedHat 的 PHP 打包程序工程师 Remi Collet 撰写了一篇新的博客文章,其中概述了一些带有示例代码的用例。

    下面摘录一个简单的例子:

    Redis 客户端

    目前存在使用 C 或 PHP 编写的 Redis 客户端的各种实现,此示例演示了使用 FFI 来访问 hiredis 库的函数。

        1. 定义库,从库的头文件 hiredis/hredis.h 和 hiredis/read.h 复制/粘贴:preload-redis.h

        2.对需要预加载的Remi\Redis 类进行定义:preload-redis.inc

        3.使用此类的测试脚本:redis.php

    输出摘要

$ php74 -d ffi.preload=preload-redis.h -d opcache.preload=preload-redis.inc redis.php...
+ Remi\Redis::__construct(localhost, 6379)
+ Remi\Redis::initFFI()
+ Remi\Redis::del(foo)int(1)
+ Remi\Redis::get(foo)NULL
+ Remi\Redis::set(foo, 2019/10/23 12:45:03)string(2) "OK"
+ Remi\Redis::get(foo)
string(19) "2019/10/23 12:45:03"
+ Remi\Redis::__destruct

    如果希望了解有关 PHP 7.4 FFI 的更多信息,可以查看 PHP.net 上的文档及其基本示例。在发布 PHP 7.4 GA 前估计会经历多个 RC 版本,GA 预计将在 11 月 28 日左右发布。

评 论

View in WeChat

Others Discussion

  • 分布式架构之「 数据分布」
    Posted on 2019-11-14 10:00
  • PHP扩展ImageMagick安装
    Posted on 2022-11-11 11:16
  • PHP7不兼容性
    Posted on 2018-03-07 15:59
  • Redis各种数据类型的使用场景举例分析【三】
    Posted on 2018-11-22 17:00
  • 投票通过,PHP 8 确认引入 Union Types 2.0
    Posted on 2019-11-18 22:22
  • PHP设计模式 - 委托模式
    Posted on 2019-04-25 16:15
  • BASE原则
    Posted on 2020-12-17 16:42
  • 程序员年中考试题-段子版
    Posted on 2021-06-23 15:57