php8自定义扩展

发布时间 2023-12-04 11:02:10作者: 朝阳1

1:进入php源码目录下的ext.如 /usr/local/php-8/ext

2.生成自定义扩展的名字 php ext_skel.php --ext python

3.撰写函数原型,编辑 python.stub.php

3.1 默认是test1,test2
    <?php

    /** @generate-function-entries */

    function all(array $arr): bool {}

    function any(array $arr): bool {}

4:根据 python.stub.php 生成 python_arginfo.h

    php ../../build/gen_stub.php python.stub.php

5.实现函数逻辑,编辑 python.c

    PHP_FUNCTION(all)
    {
        zval *input;
        zval *item;
        int result = 1, item_result = 1;
        HashTable *htbl;

        ZEND_PARSE_PARAMETERS_START(1, 1)
            Z_PARAM_ARRAY(input)
        ZEND_PARSE_PARAMETERS_END();

        htbl = Z_ARRVAL_P(input);

        ZEND_HASH_FOREACH_VAL(htbl, item) {
            item_result = zend_is_true(item);
            result &= item_result;
        } ZEND_HASH_FOREACH_END();

        RETURN_BOOL(result);
    }

    /* {{{ void any() */
    PHP_FUNCTION(any)
    {
        zval *input;
        zval *item;
        int result = 0, item_result = 0;
        HashTable *htbl;

        ZEND_PARSE_PARAMETERS_START(1, 1)
            Z_PARAM_ARRAY(input)
        ZEND_PARSE_PARAMETERS_END();

        htbl = Z_ARRVAL_P(input);

        ZEND_HASH_FOREACH_VAL(htbl, item) {
            item_result = zend_is_true(item);
            result |= item_result;
        } ZEND_HASH_FOREACH_END();

        RETURN_BOOL(result);
    }

6:执行 phpize,生成configure文件

7: ./configure && make && make install

8:加入到php.ini

    php --ini # 定位你的php.ini文件
    #添加
    extension=python.so
    #查看是否成功
    php -m | grep python

9: 测试

php -r "var_dump(all([]));"
php -r "var_dump(any([]));"