PHP C拓展开发入门笔记(一)

首先使用php拓展构建ext_skel工具构建出拓展框架

cd /path/to/php-src/ext
# 生成名为myext的C拓展框架
./ext_skel --extname=myext
#进入拓展源码目录
cd myext
#    |-config.m4 UNIX build system configuration
#    |-config.w32 Windows buildsystem configuration
#    |-
#    |-
#修改config.m4,config.m4是AutoConf工具的配置文件,用来修改各种编译选项。
vi config.m4
#dnl PHP_ARG_ENABLE(myext, whether to enable myext support,
#dnl Make sure that the comment is aligned:
#dnl [  --enable-myext           Enable myext support])
#改为
#PHP_ARG_ENABLE(myext, whether to enable myext support,
#dnl Make sure that the comment is aligned:
#[  --enable-myext           Enable myext support])

#依次执行
phpize  #used to prepare the build environment for a PHP extension
./configure
make
make install
#即可完成拓展包动态链接库的生成和安装,然后在php.ini 中加入开启拓展即可
vi php.ini
#加入 extension=myext.so
#重启apache或php-fpm



以上构建了一个默认的空拓展,下面加入一些自己写的函数并调用

//定义my_sum()函数,传递两个参数计算和并打印字符串
PHP_FUNCTION(my_sum)
{
        char * arg=NULL;
        int arg_len,len;
        char *strg;
        long i=0,j=0;
        //获取参数,详见zend函数说明:http://php.net/manual/zh/internals2.funcs.php
        if(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC,"ll",&i,&j,&arg_len) == FAILURE){
                return;
        }
        len = spprintf(&strg, 0, "%d+%d=%d\n",i,j,i+j);
        php_printf("%s\n",strg);
}
//下面函数会在查询phpinfo时显示
PHP_MINFO_FUNCTION(myext)
{
        php_info_print_table_start();
        php_info_print_table_header(2, "myext support", "enabled");
        php_info_print_table_row(2,"function my_sum","enabled");
        php_info_print_table_end();

        /* Remove comments if you have entries in php.ini
        DISPLAY_INI_ENTRIES();
        */
}

//建立zend_function_entry数组,提供给ZEND作为PHP的接口。
const zend_function_entry myext_functions[] = {
    ……
    PHP_FE(my_sum,NULL)
    ……
}
//保存重新make && make install并重启
#测试
php -r "my_sum(111,234);"

官方文档在这里:http://php.net/manual/zh/internals2.ze1.zendapi.php

猜你喜欢

转载自blog.csdn.net/guoguicheng1314/article/details/81085687