PHP扩展编写入门

本文通过编写一个简单的PHP扩展hello_world来说明PHP扩展是如何编写的。这个扩展没有任何的实用性,纯粹用来学习扩展如何编写的,如果真的想自己写出实用性的PHP扩展,还需要熟悉ZEND API,而且对C语言也有较高的要求。

好,进入正题。

1、进入PHP源码的ext目录下,然后执行:

./ext_skel --extname=hello_world

2、进入hello_world目录,编辑config.m4,去掉16行、18行和53行前面的dnl:

PHP_ARG_ENABLE(hello_world, whether to enable hello_world support,
[  --enable-hello_world           Enable hello_world support])
AC_DEFINE(HAVE_HELLO_WORLDLIB,1,[ ])

3、修改php_hello_world.h文件,把原来的

 #define PHP_HELLO_WORLD_H

改为如下内容:

#define PHP_HELLO_WORLD_H 1
#define PHP_HELLO_WORLD_VERSION "1.0"
#define PHP_HELLO_WORLD_EXTNAME "hello_world"
PHP_FUNCTION(hello_world);//这句最关键

4、修改hello_world.c文件:
把如下内容:

const zend_function_entry hello_world_functions[] = {
        PHP_FE(confirm_hello_world_compiled,    NULL)           /* For testing, remove later. */
        PHP_FE_END      /* Must be the last line in hello_world_functions[] */
};

改成:

const zend_function_entry hello_world_functions[] = {
        PHP_FE(confirm_hello_world_compiled,    NULL)           /* For testing, remove later. */ 
        PHP_FE(hello_world,    NULL)
        PHP_FE_END      /* Must be the last line in hello_world_functions[] */
};

然后在尾部加入如下内容:

//扩展函数正文部分
PHP_FUNCTION(hello_world){
        RETURN_STRING("Hello World!",1);
}

5、到ext/hello_world目录下执行如下命令

/usr/local/php/bin/phpize
./configure --with-php-config=/usr/local/php/bin/php-config
make && make install

6、编辑php.ini,增加如下内容:

extension=hello_world.so

测试:
在命令行执行如下内容:

php -r "echo hello_world();"

这时候会在标准输出那里看到如下内容:

Hello World!

至此,hello_world扩展编写完毕!

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值