c++ php扩展名,如何使用C++开发PHP扩展(下)

本文详细介绍了如何将C++编译的静态库libxxx.a集成到PHP扩展中,通过创建静态库、使用骨架脚本生成PHP扩展、修改配置文件、更新源代码以及编译和测试扩展的过程,展示了将已有的API库集成到PHP程序中的方法。
摘要由CSDN通过智能技术生成

上文中介绍了使用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!!!!!

标签: 扩展

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值