您的位置:首页 > 运维架构 > Linux

Linux下php动态添加扩展

2013-03-23 11:20 381 查看
假定手动配置好php环境情况下.................

一.生成需要调用的so文件

//要调用的算法
int RGB_TO_GRAY(int r, int g,int b)
{
return (r*299+g*587+b*114)/1000;
}


$ gcc -O -c -fPIC -o gray.o gray.c // -fPIC:是指生成的动态库与位置无关

$ gcc -shared -o libgray.so gray.o // -shared:是指明生成动态链接库 libgray.so 指明后面调用库时要调用lgray

# cp libgray.so /usr/local/lib          // 把生成的链接库放到指定的地址

# echo /usr/local/lib > /etc/ld.so.conf.d/local.conf // 把库地址写入到配置文件中

# /sbin/ldconfig              // 用此命令,使刚才写的配置文件生效

写段程序验证其正确性:

#include <stdio.h>
int main()
{
int a = 3, b = 4,c =5;
printf("r=%d g= %d b= %d ,then gray=%d", a, b,c,RGB_TO_GRAY(a,b,c));

return 0;
}


编译并执行:
$ gcc -o test -lgray test.c // 编译测试文件,生成测试程序
$ ./test // 运行测试程序

二.制作PHP模块 (外部模块)

为了方便操作设定一些环境变量,当然也可以不用。

php源码解压地址为$php-5.3.23

php安装地址为$php

apache安装地址为$apache2

1、创建名字为gray的项目,最终会生成gray.so

  cd $php-5.3.23/ext/
  ./ext_skel --extname=gray

2、 首先编辑生成的gray文件夹内的 config.m4 文件,去掉第16行~第18行的注释(注释符号为 dnl 。)
  $ gedit gray/config.m4
修改成
  PHP_ARG_ENABLE(gray, whether to enable gray support,
  Make sure that the comment is aligned:
  [ --enable-gray Enable gray support])

3. 打开 php_gray.h, $ gedit gray/php_gray.h


  PHP_FUNCTION(confirm_gray_compiled); /* For testing, remove later. */
更改为
  PHP_FUNCTION(gray);

 打开gray.c $ gedit gray/gray.c

  zend_function_entry php5cpp_functions[] = {
  PHP_FE(confirm_gray_compiled, NULL) /* For testing, remove later. */
  {NULL, NULL, NULL} /* Must be the last line in php5cpp_functions[] */
  };
更改为
  zend_function_entry php5cpp_functions[] = {
  PHP_FE(gray, NULL)
  {NULL, NULL, NULL} /* Must be the last line in php5cpp_functions[] */
  };
在文件最后添加:

  PHP_FUNCTION(gray)
  {
    long int r,g,b;
    long int result;    
    if(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC,"lll",&r,&g,&b)==FAILURE){
      return;
    }
    result=RGB_TO_GRAY(r,g,b);
    RETURN_LONG(result);
  }

4. 然后执行 phpize 程序,生成configure脚本:

  $ cd $php-5.3.23/ext/gray
  $ $php/bin/phpize

ps: 如果出现:Cannot find autoconf.……的错误信息,则需要安装 autoconf (安装过程略)

$ ./configure --with-php-config=$php/bin/php-config
$ make LDFLAGS=-lgray  //调用一开始放入配置的动态链接库
$ make install     //这时会编译出 gray/modules/gray.so

5.配置php.ini     //该文件所在目录可通过在浏览器中执行phpinfo();方法的php文件查询
  将gray.so放入目录假定$php/ext/
  $ gedit php.ini
  修改extension_dir并添加扩展如下:
  extension_dir = '$php/ext/'
  extension=gray.so
6.测试
  $ gedit $apache2/htdocs/test.php  //编写测试php文件

  <?php
    echo gray(20,30,55);
  ?>

7:重启Apache

# $apache2/bin/apachectl restart

在浏览器localhost/test.php查看输出  29  

结束···
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: