Linux下使用C++来编写PHP扩展库
一、获取并解压缩PHP
wget http://docs.php.net/get/php-5.2.5.tar.bz2/from/cn.php.net/mirror
tar -jxf php-5.2.5.tar.bz2
cd php-5.2.6/ext
./ext_skel --extname=php_cxx_sample
注:php_cxx_sample为扩展库的名字
二、扩展库文件说明
cd php_cxx_sample
ll
该目录下有如下一些文件:
config.m4
config.w32
php_cxx_sample.c
php_cxx_sample.php
php_php_cxx_sample.h
tests
其中php_cxx_sample.c是库的源代码,php_php_cxx_sample.h是库的头文件,php_cxx_sample.php是调用范例
因为我们是用C++,将php_cxx_sample.c改为php_cxx_sample.cpp
三、编辑CPP文件
打开php_cxx_sample.cpp,用extern "C"{}讲#include一段和ZEND_GET_MODULE(php_cxx_sample)括起来,如下:
extern "C"
{
#include "php.h"
#include "php_ini.h"
#include "ext/standard/info.h"
#include "php_php_cxx_sample.h"
}
#ifdef COMPILE_DL_MYTEST
extern "C"
{
ZEND_GET_MODULE(php_cxx_sample)
}
#endif
四、编译准备工作
vi ext/php_cxx_sample/configure.m4,编辑该文件,如下:
PHP_ARG_WITH(php_cxx_sample, for php_cxx_sample support,
Make sure that the comment is aligned:
[ --with-php_cxx_sample Include php_cxx_sample support])
if test "$PHP_PHP_CXX_SAMPLE" == "yes"; then
PHP_REQUIRE_CXX()
PHP_SUBST(PHP_CXX_SAMPLE_SHARED_LIBADD)
PHP_ADD_LIBRARY(stdc++,"",PHP_CXX_SAMPLE_SHARED_LIBADD)
PHP_NEW_EXTENSION(php_cxx_sample, php_cxx_sample.cpp, $ext_shared)
五、编译
/usr/local/php/bin/phpize
./configure --with-php-config=/usr/local/php/bin/php-config --with-php_cxx_sample=shared
make
make install
注,编译完成后的so文件在php_cxx_sample目录下的moudles目录下
六、最后的准备工作
修改php.ini,找到php安装的配置文件,修改extension_dir条目的下面添加:
extension=php_cxx_sample.so
重新启动Nginx或Apach,将php_cxx_sample.php拷贝到网站主目录下面,通过浏览器访问看到configuration字样表示扩展库工作常