ITeye博客

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

xiaodi667 · 2012-07-11 17:37 · php · 编程语言 · Markdown

安装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-config
make
make 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-config
make
make install

 重启apache或者nginx

 

在PHP脚本里面直接调用roger_test(”hello kitty! “),结果:

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。