为什么要用c扩展

c是静态编译的,执行效率比php代码高很多。同样的运算代码,使用c来开发,性能会比php要提升数百倍。io操作如curl,因为耗时主要在iowait上,c扩展没有明显优势。

另外c扩展是在进程启动时加载的,php代码只能操作request生命周期的数据,c扩展可操作的范围更广。

第一步

下载php的源代码,如php-5.4.16。解压后进入php-5.4.16\ext目录。输入 ./ext_skel –extname=myext,myext就是扩展的名称,执行后生成myext目录。

ext_skel是php官方提供的用于生成php扩展骨架代码的工具。

cd myext。可以看到php_myext.h、myext.c、config.m4等几个文件。config.m4是autoconf工具的配置文件,用来修改各种编译选项。

第二步

修改config.m4,将

dnl php_arg_with(myext, for myext support,

dnl make sure that the comment is aligned:

dnl [ --with-myext       include myext support])

修改为

php_arg_with(myext, for myext support,

[ --with-myext       include myext support])

下边还有一个 –enable-myext,是表示编译到php内核中。with是作为动态链接库载入的。

第三步

修改php_myext.h,看到php_function(confirm_myext_compiled); 这里就是扩展函数声明部分,可以增加一行 php_function(myext_helloworld); 表示声明了一个myext_helloworld的扩展函数。

然后修改myext.c,这个是扩展函数的实现部分。

const zend_function_entry myext_functions[] = {

    php_fe(confirm_myext_compiled, null)      /* for testing, remove later. */

    php_fe(myext_helloworld, null)

    php_fe_end   /* must be the last line in myext_functions[] */

};

这的代码是将函数指针注册到zend引擎,增加一行php_fe(myext_helloworld, null)(后面不要带分号)。

第四步

在myext.c末尾加myext_helloworld的执行代码。

php_function(myext_helloworld)

{

    char *arg = null;

  int arg_len, len;

  char *strg;

  if (zend_parse_parameters(zend_num_args() tsrmls_cc, "s", &arg, &arg_len) == failure) {

    return;

  }

  php_printf("hello world!\n");

  retrun_true;

}

zend_parse_parameters是用来接受php传入的参数,return_xxx宏是用来返回给php数据。

第五步

在myext目录下依次执行phpize、./configure 、make、make install。然后修改php.ini加入extension=myext.so

执行php -r “myext_helloworld(‘test’);”,输出hello world!