如何使用C创建php扩展2015-01-16使用C创建php扩展优点:1.提高运行效率。2.降低php复杂度,可以直接调用扩展方法实现功能。3.方便与第三方库交互。缺点:1.开发比php复杂。2.可维护性降低。3.开发周期变长。php开发,发现问题后,只要修复问题,即可见到效果。如果使用扩展,修复后需要重新编译,重启服务,才能见到效果。首先,假定需要实现一个方法:将url字符串转换成超链接。php实现方法:
<?phpfunction strtolink($url, $name="", $openwin=0){$name = $name==""? $url : $name;$openwin = $openwin==1? " target="_blank" " : "";return "<a href="".$url."" ".$openwin.">".$name."</a>";}echo strtolink("http://blog.csdn.net/fdipzone", "fdipzone blog", 1);?>
现在使用C来做这个方法的扩展,开发php扩展需要使用ext_skel工具包,此工具包在php安装包的 /ext/ 中,例如:php-5.3.15/ext/ext_skel1.创建 skel 文件,保存为 strtolink.skelstring strtolink(string url, string name, int openwin)2.创建扩展框架./ext_skel --extname=strtolink --proto=strtolink.skelcd strtolink3.修改配置文件 config.m4
将这10,11,12三行前面的 dnl 去掉dnl PHP_ARG_WITH(strtolink, for strtolink support,dnl Make sure that the comment is aligned:dnl [--with-strtolink Include strtolink support])即修改为:PHP_ARG_WITH(strtolink, for strtolink support,Make sure that the comment is aligned:[--with-strtolink Include strtolink support])
4.实现功能,修改strtolink.c,将PHP_FUNCTION(strtolink)这个方法修改为:
PHP_FUNCTION(strtolink){char *url = NULL;char *name = NULL;int argc = ZEND_NUM_ARGS();int url_len;int name_len;long openwin = 0;char *opentag;char *result;if (zend_parse_parameters(argc TSRMLS_CC, "s|sl", &url, &url_len, &name, &name_len, &openwin) == FAILURE)return;if (name == NULL || strlen(name)==0){name = url;}if (openwin == 1){opentag = " target="_blank" ";}else{opentag = "";}url_len = spprintf(&result, 0, "<a href="%s" %s>%s</a>", url, opentag, name);RETURN_STRINGL(result, url_len, 0);php_error(E_WARNING, "strtolink: not yet implemented");}