php扩展开发 汇编,PHP扩展开发

为什么要用到php扩展?因为php扩展使用C语言编写,而C语言是静待编译的,所以执行效率要高于php很多,这里我来实现一个完成一个简单的Helloworld函数的例子。

生成框架

首先我们要生成扩展开发的框架,先下载php的源码,在php的源码/ext/目录下有一个文件ext_skel,他是专门用来生成扩展开发必要文件的文件。

命令:

tongkundeMacBook-Pro:ext tongkun$ ./ext_skel --extname=Helloworld

Creating directory Helloworld

Creating basic files: config.m4 config.w32 .gitignore Helloworld.c php_Helloworld.h CREDITS EXPERIMENTAL tests/001.phpt Helloworld.php [done].

To use your new extension, you will have to execute the following steps:

1. $ cd ..

2. $ vi ext/Helloworld/config.m4

3. $ ./buildconf

4. $ ./configure --[with|enable]-Helloworld

5. $ make

6. $ ./sapi/cli/php -f ext/Helloworld/Helloworld.php

7. $ vi ext/Helloworld/Helloworld.c

8. $ make

Repeat steps 3-6 until you are satisfied with ext/Helloworld/config.m4 and

step 6 confirms that your module is compiled into PHP. Then, start writing

code and repeat the last two steps as often as necessary.

这样就会在ext目录下生成Helloworld目录,目录里有config.m4、haosoft_php_module.h和haosoft_php_module.c等几个文件

配置文件

首先修改config.m4文件,删除下面三项前面的dnl注释。

##动态编译选项,通过.so的方式链接,去掉dnl注释

PHP_ARG_WITH(Helloworld, for Helloworld support,

[ --with-Helloworld Include Helloworld support])

##静态编译选项,通过enable来启用,去掉dnl注释

PHP_ARG_ENABLE(Helloworld, whether to enable Helloworld support,

[ --enable-Helloworld Enable Helloworld support])

修改完成编译一下,依次执行以下命令:

phpize

./configure --enable-Helloworld

make

make install

以上命令执行后,会在扩展目录生成Helloworld.php的测试文件,测试文件已动态的方式加载扩展进行测试,执行:

#执行

php -d enable_dl=On Helloworld.php

#输出

Functions available in the test extension:

confirm_Helloworld_compiled

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

通过设置enable_dl=On的方式开启php动态加载,输出如上内容说明扩展编译成功

修改代码,实现功能

通过vim打开Helloworld.c文件

找到PHP_FUNCTION(confirm_Helloworld_compiled)函数,修改为:

PHP_FUNCTION(Helloworld)

{

php_printf("Hello World!\n");

RETURN_TRUE;

}

修改函数定义处:

const zend_function_entry Helloworld_functions[] = {

PHP_FE(Helloworld, NULL) /* For testing, remove later. */

PHP_FE_END /* Must be the last line in Helloworld_functions[] */

};

重新编译,这里要带上php-config 目录

./configure --with-php-config=/usr/local/Cellar/php56/5.6.24/bin/php-config

make

make install

这时在module目录下就会生成Helloworld.so 文件,拷贝到php的扩展目录,可以参见php.ini 中的ext_dir 配置

cp modules/Helloworld.so /usr/local/etc/php/5.6/extensions/

重启php-fpm,然后在php中直接调用Helloworld即可输出Hellowold 说明测试完成

对于在php扩展中怎样使用zval变量,C语言函数等在后续学习补充。

参考:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值