给 PHP 写 C 扩展

2022/08/10 PHP

前期准备

源码编译安装 PHP。本文使用的是 PHP-8.1,其它版本可能会有所差异。

$ # 获取 PHP 源码并编译
$ git clone https://github.com/php/php-src.git
$ git checkout PHP-8.1
$ cd php-src
$ ./buildconf
$ ./configure
$ make
$ make install

生成扩展基本骨架

安装 PHP 之后,进入 PHP 源码的扩展目录,通过 PHP 提供的脚本生成扩展的基本骨架,hello为扩展名。

$ cd ext
$ php ext_skel.php --ext hello

添加自定义函数

以上脚本生成的扩展骨架其实已经在两个默认函数test1test2了,我们尝试添加自己的函数test3

$ cd hello
$ vim hello.c

hello.c中添加函数test3

// hello.c
PHP_FUNCTION(test3)
{
    php_printf("Hello world from my first C extension\n"); 
}

除此之外,还要将函数原型添加到hello.stub.php中。

$ vim hello.stub.php

在以上的hello.stub.php中添加以下代码:

// hello.stub.php
function test3(): void {}

编译安装扩展

$ phpize
$ ./configure
$ make
$ make install

配置并测试

编辑php.ini加入extension=hello

现在,第一个为 PHP 编写的 C 扩展已经编译安装完成。来看看效果吧。

$ php -m | grep hello
hello
$ php --re hello
Extension [ <persistent> extension #26 hello version 0.1.0 ] {

  - Functions {
    Function [ <internal:hello> function test1 ] {

      - Parameters [0] {
      }
      - Return [ void ]
    }
    Function [ <internal:hello> function test2 ] {

      - Parameters [1] {
        Parameter #0 [ <optional> string $str = "" ]
      }
      - Return [ string ]
    }
    Function [ <internal:hello> function test3 ] {

      - Parameters [0] {
      }
      - Return [ void ]
    }
  }
}

运行扩展函数试试。

$ php -r 'test3();'
Hello world from my first C extension

Search

    Table of Contents