上文中介绍了使用C++编写简单PHP扩展的方法,但是更多的情况是业务中已经有独立的 api 库,形式为 libxxx.a / libxxx.so,PHP程序中需要调用这些 api,所以这时就要编写PHP扩展来实现。这时是使用静态库 libxxx.a ,还是使用 libxxx.so 呢 ?常见的做法是使用静态库 libxxx.a ,下面一步一步介绍:
1. 创建静态库
1.1 执行命令及内容如下:
[root@localhost ~]# mkdir libhello
[root@localhost ~]# cd libhello/
[root@localhost libhello]# vim hello.h
[root@localhost libhello]# vim hello.cpp
hello.h
#include
using namespace std;
string say();
hello.cpp
#include "hello.h"
string say()
{
string str = "Hello World!!!!!";
return str;
}
1.2 编译为 libhello.a (可参考:
2. 使用骨架脚本生成PHP扩展 discuz(可参考:
3. 把 hello.h,libhello.a 放到 PHP扩展文件夹中,如下:
[root@localhost ~]# cp libhello/libhello.a php-5.3.24/ext/discuz/lib
cp:是否覆盖“php-5.3.24/ext/discuz/lib/libhello.a”? y
[root@localhost ~]# cp libhello/hello.h php-5.3.24/ext/discuz/include/
cp:是否覆盖“php-5.3.24/ext/discuz/include/hello.h”? y
4. 修改 config.m4,内容如下:
dnl $Id$
dnl config.m4 for extension discuz
PHP_ARG_ENABLE(discuz, whether to enable discuz support,
Make sure that the comment is aligned:
[ --enable-discuz Enable discuz support])
if test "$PHP_DISCUZ" != "no"; then
PHP_REQUIRE_CXX()
PHP_ADD_LIBRARY(stdc++, 1, EXTRA_LDFLAGS)
dnl set include path
PHP_ADD_INCLUDE(./include)
dnl checking libhello.a is exists or not
AC_MSG_CHECKING([for lib/libhello.a])
if test -f ./lib/libhello.a; then
AC_MSG_RESULT([yes])
PHP_ADD_LIBRARY_WITH_PATH(hello, ./lib, EXTRA_LDFLAGS)
else
AC_MSG_RESULT([not found])
AC_MSG_ERROR([Plaese check ./lib/libhello.a])
fi
PHP_NEW_EXTENSION(discuz, discuz.cpp, $ext_shared)
fi
5. 修改discuz.cpp
5.1 添加头文件
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#include "php_ini.h"
#include "ext/standard/info.h"
#include "php_discuz.h"
#include
#include "hello.h"
5.2 修改 discuz_say 函数,如下:
/* {{{ proto string discuz_say()
*/
PHP_FUNCTION(discuz_say)
{
string str = say();
RETURN_STRINGL(str.c_str(), str.length(), 1);
}
6. 编译扩展(可参考:)
7. 开始测试吧
[root@localhost ~]# /usr/local/php-5.3.24/bin/php hi.php
Hello World!!!!!
标签: 扩展