六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 35|回复: 0

Ubuntu下用C编写PHP扩展 例子展示 绝对详细

[复制链接]

升级  0.67%

13

主题

13

主题

13

主题

秀才

Rank: 2

积分
51
 楼主| 发表于 2013-1-26 12:29:13 | 显示全部楼层 |阅读模式
安装php5-dev
 
sudo apt-get install php5-dev  下载PHP源码
 
sudo apt-get source php5 创建模块模型
 
cd ./php-5.3.2/ext./ext_skel --extname=roger 

 

进入roger目录,这里主要编辑的文件有两个:config.m4和roger.c,config.m4可以配置扩展编译进php的方法,roger.c是编码模块的主要文件。使用vim编辑config.m4文件,找到以下几行:


 改变为:


 退出保存(roger.c暂时不做修改);
执行命令phpize,phpize是用来扩展php模块的,完成后可以看到产生了./configure程序:


 安装
 
./configure --with-php-config=/usr/bin/php-configmakemake install 

查看生成的roger.so:


修改php.ini加载roger.so,重启apache;
 
查看phpinfo(),可以看到roger.so已经加载:


 创建一个php文件,写入:


 运行结果:


============================== 自定义函数==============================
如果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! “),结果:

您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表