编写php扩展hello_world(),简单实现

先简单实现扩展编写

php7.1

1.下载一个源码包,进入ext目录,该目录下有个ext_skel脚本

2.执行命令 ./ext_skel --extname=hello ,命名扩展名

ext_skel自动生成扩展文件编写骨架

3.生成骨架之后需要进行一定的修改

config.m4 文件

    
    # config.mg 文件中 dnl 是代码注释标识符
    
    dnl PHP_ARG_ENABLE(hello, whether to enable hello support,
    dnl Make sure that the comment is aligned:
    dnl [  --enable-hello           Enable hello support])

    #  删除 第一行和第三行的dnl [去除注释]
    

hello.c 文件

//每添加一个函数都要在这里面声明zend函数入口

const zend_function_entry hello_functions[] = {
    PHP_FE(confirm_hello_compiled,  NULL)       /* For testing, remove later. */
    
    //这是新声明的函数
    PHP_FE(hello_world,  NULL)
    
    PHP_FE_END  /* Must be the last line in hello_functions[] */
};

//注册完之后编写函数主体
//直接把原来的confirm_hello_compiled函数主体copy过来了

PHP_FUNCTION(hello_world)
{
    char *arg = NULL;
    size_t arg_len, len;
    zend_string *strg;
    if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &arg, &arg_len) == FAILURE) {
         return;
    }

    strg = strpprintf(0, "Congratulations! You have successfully modified ext/%.78s/config.m4. Module %.78s is now compiled into PHP.", "hello", arg);

    RETURN_STR(strg);
}



    #编译安装扩展

    #我是能正常安装,所以一条执行
    phpize && ./configure && make && make install

正常生成扩展之后,在php配置文件中加入新的扩展 extension=hello.so

cli模式下直接 php -r "echo hello_world('厉害啊')";

fpm需要重启php-fpm服务

猜你喜欢

转载自my.oschina.net/u/3095457/blog/1794136