三分钟编写PHP可扩展模块

来源:互联网 发布:单片机乐谱 编辑:程序博客网 时间:2024/05/02 00:43
(本文由 song.xian-guang 原创,如果您觉得对您有帮助,请评论之,如需转载,请指明链接;作者保留所有权利, 禁止商业用途)

根据我的提示,三分钟内你就能制作自己的PHP可扩展模块:
 
第一步:搭建模块框架
下载并解压php源代码,配置、编译、安装:
[root@localhost php-ext-demo]# tar jxvf php-5.2.5.tar.bz2
假设模块名字是sxgsystem,则运行如下命令生成模块框架:
[root@localhost ext]# pwd
/home/sxg/php-ext-demo/php-5.2.5/ext
[root@localhost ext]# ./ext_skel --extname=sxgsystem

进入目录sxgsystem,可以看到上述命令生成了不少文件,留下三个文件php_sxgsystem.h、sxgsystem.c、sxgsystem.php,其余的都删除掉
[root@localhost ext]# cd sxgsystem
[root@localhost sxgsystem]# ls
config.m4  config.w32  CREDITS  EXPERIMENTAL  php_sxgsystem.h  sxgsystem.c  sxgsystem.php  tests
[root@localhost sxgsystem]# rm -rf config.m4  config.w32  CREDITS  EXPERIMENTAL  tests

加入一个Makefile后(请适当修改, 替换sxgsystem、SXGSYSTEM成为你的模块名字),就可以编译了:
[root@localhost sxgsystem]# cat Makefile 
SO_NAME   = sxgsystem
PHP_SRC   = ../php-5.2.5
TARGET    = $(SO_NAME).so
OBJS      = $(SO_NAME).o
CC        = gcc
CFLAGS    = -Wall -fpic -DCOMPILE_DL=1 -DCOMPILE_DL_SXGSYSTEM
INCLUDE   = -I$(PHP_SRC) -I$(PHP_SRC)/main -I. -I$(PHP_SRC)/TSRM -I$(PHP_SRC)/Zend
TARGET: $(OBJS)
        $(CC) -shared -L/usr/local/lib -rdynamic -o $(TARGET) $(OBJS)
%.o:%.c
        $(CC) $(CFLAGS) $(INCLUDE) -o $@ -c $<
clean:
        rm -f *.o $(TARGET)

第二步:添加函数框架
在php_sxgsystem.h中添加函数声明:
PHP_FUNCTION(get_memory_info);
PHP_FUNCTION(get_cpu_info); 
 
在sxgsystem.c中填充入口,并实现之:
zend_function_entry sxgsystem_functions[] = {
 PHP_FE(get_memory_info, NULL)  /* Get Memory information */
 PHP_FE(get_cpu_info, NULL)  /* Get CPU information */
 {NULL, NULL, NULL} /* Must be the last line in sxgsystem_functions[] */
};
 
PHP_FUNCTION(get_memory_info)
{
 long ret;
 
 zend_printf("get_memory_info is called\n");
 
 RETURN_LONG(ret);
}
PHP_FUNCTION(get_cpu_info)
{
 long ret;
 
 zend_printf("get_cpu_info is called\n");
 
 RETURN_LONG(ret);
}
 
编译生成sxgsystem.so:
[root@localhost sxgsystem]# make
 
用sxgsystem.php进行测试:
//sxgsystem.php
$br = (php_sapi_name() == "cli")? "":"
";
$module = "sxgsystem";
$MY_LIB = $module . "." . PHP_SHLIB_SUFFIX;
if(!extension_loaded(module))
{
 echo "loading php extention module : $MY_LIB... ";
 dl($MY_LIB);
 echo "done$br\n";
}
$functions = get_extension_funcs($module);
echo "Functions available in the test extension:$br\n";
foreach($functions as $func) {
    echo $func."$br\n";
}
echo "$br\n";
get_memory_info();
get_cpu_info();
?>
 
测试一下:
[root@localhost sxgsystem]# php -f sxgsystem.php 
loading php extention module : sxgsystem.so... done
Functions available in the test extension:
get_memory_info
get_cpu_info
get_memory_info is called
get_cpu_info is called
注:执行的时候会提示sxgsystem.so不在某个目录中,手动拷贝过去即可。
 
第三步:补充完整所添加的函数
第四步:编译打包成so发布
 
另外,用C++写PHP扩展模块时,由于涉及到C和C++的名称转换问题,需要对C定义的头文件用extern "C"包围起来。
 
sxg

0 0
原创粉丝点击