Ubuntu下用C编写PHP扩展 例子展示 绝对详细
安装php5-devsudo apt-get install php5-dev 下载PHP源码
sudo apt-get source php5 创建模块模型
cd ./php-5.3.2/ext./ext_skel --extname=roger
http://dl.iteye.com/upload/attachment/0070/6161/c0aae05a-6713-3e94-a08c-9112e6f1a477.png
http://dl.iteye.com/upload/attachment/0070/6164/442057fa-df4a-34e8-9bd0-62127b726d7b.png
进入roger目录,这里主要编辑的文件有两个:config.m4和roger.c,config.m4可以配置扩展编译进php的方法,roger.c是编码模块的主要文件。使用vim编辑config.m4文件,找到以下几行:
http://dl.iteye.com/upload/attachment/0070/6167/ed7f1de4-5730-38fc-957d-9c9f59129969.png
改变为:
http://dl.iteye.com/upload/attachment/0070/6171/e982b563-04c3-3e5a-8224-5a36300f7a3f.png
退出保存(roger.c暂时不做修改);
执行命令phpize,phpize是用来扩展php模块的,完成后可以看到产生了./configure程序:
http://dl.iteye.com/upload/attachment/0070/6175/5fbfc4e3-30ec-31f5-b48f-06cca8421cf3.png
安装
./configure --with-php-config=/usr/bin/php-configmakemake install
http://dl.iteye.com/upload/attachment/0070/6177/ee1bab95-6901-308b-a900-443240c09ef4.png
查看生成的roger.so:
http://dl.iteye.com/upload/attachment/0070/6179/1c07c889-8f9a-3435-8422-325861fc93db.png
修改php.ini加载roger.so,重启apache;
查看phpinfo(),可以看到roger.so已经加载:
http://dl.iteye.com/upload/attachment/0070/6183/16f0ab5e-c151-36d3-b4dd-8d36cfed4c82.png
创建一个php文件,写入:
http://dl.iteye.com/upload/attachment/0070/6189/eca07376-b894-31f3-b6b2-95e8acc0f178.png
运行结果:
http://dl.iteye.com/upload/attachment/0070/6193/2d0d2d7a-5f61-37d6-ad51-0735ade05433.png
============================== 自定义函数==============================
如果roger.c不做任何修改,会有一个自带的函数confirm_roger_compiled,输出的结果就是上面看到的,下面自定义一个函数。
函数名:roger_test($str)
功能:返回 “your input string:”.$str;
重复上面的步骤,修改完config.m4,接着修改php_roger.h和roger.c;
vim php_roger.h
找到:PHP_FUNCTION(confirm_roger_compiled); ,新增一行:
PHP_FUNCTION(roger_test);
PHP_FUNCTION(confirm_roger_compiled); /* For testing, remove later. */PHP_FUNCTION(roger_test); /* For testing, remove later. */ 保存退出。
vim roger.c
数组里增加我们的函数,找到 const zend_function_entry roger_functions[] ,增加:
PHP_FE(roger_test, NULL)
const zend_function_entry roger_functions[] = { PHP_FE(confirm_roger_compiled, NULL) /* For testing, remove later. */ PHP_FE(roger_test, NULL)/* For testing, remove later. */ {NULL, NULL, NULL} /* Must be the last line in roger_functions[] */};
保存退出。
再到 roger.c 文件最后面增加如下代码:
PHP_FUNCTION(roger_test){ char *arg = NULL; int arg_len, len; char *strg; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &arg, &arg_len) == FAILURE) { return; } len = spprintf(&strg, 0, "your input string: %s\n", arg); RETURN_STRINGL(strg, len, 0);}
继续执行如下命令
./configure --with-php-config=/usr/bin/php-configmakemake install 重启apache或者nginx
在PHP脚本里面直接调用roger_test(”hello kitty! “),结果:
http://dl.iteye.com/upload/attachment/0070/6202/3ae0bbe0-e4da-3bd9-98fe-49d031ceec5c.png
页:
[1]