php扩展之关于hello world的详细介绍

黄舟
黄舟 原创
2023-03-15 07:10:01 1450浏览


前言

这是一篇拖了很久就想写的备忘录,编写php扩展一百度都是文章,但是很多文章是很老的了。有的例子都跑不通。有点尴尬。
此文用于记录自己的笔记,当作备忘录。

正文

1. 下载php安装包

下载地址:php下载快链
本文选取的是php-5.6.7安装包。
之后安装php。

2. 创建扩展骨架

//跑到ext目录cd php-5.6.7/ext///执行一键生成骨架的操作./ext_skel --extname=helloworld

如果看到以下提示说明创建成果
这里写图片描述

cd helloworld
ls

一下你会发现有如下文件:

config.m4  config.w32  CREDITS  EXPERIMENTAL  helloworld.c  helloworld.php  php_helloworld.h  tests

3. 修改扩展的配置文件config.m4

去掉下面代码之前的dnl 。(dnl相当于php的//)

##动态编译选项,通过.so的方式链接,去掉dnl注释PHP_ARG_WITH(helloworld, for helloworld support,
Make sure that the comment is aligned:
[  --with-helloworld             Include helloworld support])##静态编译选项,通过enable来启用,去掉dnl注释PHP_ARG_ENABLE(helloworld, whether to enable helloworld support,
Make sure that the comment is aligned:
[  --enable-helloworld           Enable helloworld support])

一般二者选一即可(看个人喜好吧,本文教程必须去掉enable的注释)。

4. 进行编译测试

phpize
./configure --enable-helloworldmakemake install

然后到php.ini添加一下扩展

vim /usr/local/php/etc/php.ini// 添加扩展extension_dir = "/usr/local/php/lib/php/extensions/no-debug-non-zts-20131226/"extension = "helloworld.so"// 重启php-fpm/etc/init.d/php-fpm restart

回到写扩展的文件夹,执行测试命令

php -d enable_dl=On myfile.php

看到如下字样说明离胜利不远了:

confirm_helloworld_compiled

Congratulations! You have successfully modified ext/helloworld/config.m4. Module helloworld is now compiled into PHP.

confirm_helloworld_compiled是ext_skel自动生成的测试函数。

ps:如果本地安装了两个php版本,并且是用php7编写扩展的话,可能会遇到以下问题:

/mydata/src/php-7.0.0/ext/helloworld/helloworld.c: 在函数‘zif_confirm_helloworld_compiled’中:
/mydata/src/php-7.0.0/ext/helloworld/helloworld.c:58: 错误:‘zend_string’未声明(在此函数内第一次使用)
/mydata/src/php-7.0.0/ext/helloworld/helloworld.c:58: 错误:(即使在一个函数内多次出现,每个未声明的标识符在其
/mydata/src/php-7.0.0/ext/helloworld/helloworld.c:58: 错误:所在的函数内也只报告一次。)
/mydata/src/php-7.0.0/ext/helloworld/helloworld.c:58: 错误:‘strg’未声明(在此函数内第一次使用)

原因:编译的环境不是php7。
解决办法:php5 里面没有zend_string类型,用 char 替换,或者,修改你的php版本环境到php7

5. 创建helloworld函数

编辑helloworld.c,补充要实现的函数

##zend_function_entry helloworld_functions 补充要实现的函数const zend_function_entry helloworld_functions[] = { 
    PHP_FE(confirm_helloworld_compiled, NULL)       /* For testing, remove later. */
    PHP_FE(helloworld,  NULL)       /* 这是补充的一行,尾巴没有逗号 */
    PHP_FE_END  /* Must be the last line in helloworld_functions[] */};

找到”PHP_FUNCTION(confirm_helloworld_compiled)”,另起一个函数编写函数实体:

PHP_FUNCTION(helloworld) {    php_printf("Hello World!\n");
    RETURN_TRUE;
}

再走一遍编译:

./configure --enable-helloworld && make && make install

测试一下是不是真的成功了:

php -d enable_dl=On -r "dl('helloworld.so');helloworld();"//输出Hello World!

成功!

以上就是php扩展之关于hello world的详细介绍的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。