php调用C语言生成的so文件

来源:互联网 发布:golang教程 pdf 编辑:程序博客网 时间:2024/04/30 05:23

最近小编一直在研究php调用C语言生成的so文件问题,网上查阅了许多相关的资料,但是大多数文章的操作都不是在MAC OS X 系统上进行的,这让小编很是苦恼。但是经过一周多的种种尝试,小编终于解决了这个问题,在此和大家分享一下,仅供参考学习。
文末附加网上的参考资料

在进入正题之前,小编先给大家介绍使用gcc命令生成so文件的方法步骤。

  • 创建hello.c文件,在终端执行命令
vim hello.c
  • 编辑hello.c文件,内容如下
int zq_add(int a, int b){    return a + b;}
  • 生成.o文件,在终端执行命令
 // -fPIC:是指生成的动态库与位置无关  gcc -O -c -fPIC -o hello.o hello.c      
  • 生成.so文件,在终端执行命令
// -shared:是指明生成动态链接库 gcc -shared -o libhello.so hello.o      
  • 把库地址写入到配置文件中,在终端执行命令
sudo sh -c "echo '/usr/local/lib' >> /private/etc/ld.so.conf.d/local.conf"
  • 创建hellotest.c测试文件,在终端执行命令
vim hellotest.c
  • 编辑hellotest.c文件,内容如下
#include <stdio.h>#include "hello.c"int main(){int a = 3, b = 4;printf("%d + %d = %d\n", a, b, zq_add(a, b));return 0;}
  •  编译测试文件,生成测试程序,在终端执行命令
gcc -o hellotest -lhello hellotest.c
  •   运行测试程序,在终端执行命令
./hellotest                            

言归正传,解决php调用C语言生成的so文件问题的思路是这样的:写一个php模块(php extension),在php中调用该模块内的函数,再通过该模块来调用so中的函数。

– 当然也是有前提的,搭建php的开发环境

搭建php的开发环境

  • mac自带php,具体操作参考文末链接

在php官网上下载php源代码(最好是5)

  • 下载地址见文末链接

编写php模块php extension

  • 在php源代码根目录下,在终端依次执行命令:
./buildconf --force./configure --prefix=/usr/local/php7 --with-apxs2=/usr/sbin/apxs --enable-fpm --with-fpm-user=www --with-fpm-group=www --with-mysqli --with-pdo-mysql --with-iconv-dir --with-freetype-dir --with-jpeg-dir --with-png-dir --with-zlib --with-libxml-dir=/usr --enable-xml --disable-rpath --enable-bcmath --enable-shmop --enable-sysvsem --enable-inline-optimization --with-curl --enable-mbregex --enable-mbstring --with-mcrypt --enable-ftp --with-gd --enable-gd-native-ttf --with-openssl --with-mhash --enable-pcntl --enable-sockets --with-xmlrpc --enable-zip --enable-soap --without-pear --with-gettext --disable-fileinfo --enable-maintainer-zts
  • 在php源代码的ext目录下,在终端执行命令:
./ext_skel --extname=php扩展名称
  • 在php源代码/ext/php扩展名称 目录下,修改config.m4文件,再在终端执行命令:
phpize
  • 在当前目录下,在终端依次执行命令:
./configure  sudo make   make test  sudo make install
  • 在终端执行命令:php -i | grep php.ini,并在php.ini文件中添加代码:
extension_dir =  执行sudo make install命令之后的地址extension=php扩展名称.so
  • 重启,在终端执行命令:
sudo /usr/sbin/apachectl restart
  • 检测扩展是否可用,在终端执行命令:
php -r 'echo confirm_php扩展名称_compiled("Hello World!");'

–至此PHP扩展的骨架已经搭建完成

编写php内部模块

  • 将所要调用的函数所在的.c文件移至骨架模块中
  • 在骨架模块的.h文件中添加自定义的方法名
  • 在骨架模块的.c文件中添加所要调用的函数所在的.c文件的引用,再在“zend_function_entry hello_functions[]”中注册自定义的方法名,最后在文件末尾编写实现自定义方法的业务逻辑代码
  • 再次安装php扩展模块,并重新启动php,在终端依次执行命令:
sudo make installsudo /usr/sbin/apachectl restart
  • 检测扩展是否可用,在终端执行命令:
php -r 'echo 自定义方法名;'
-----------------------------------END--------------------------------

http://jingyan.baidu.com/article/67508eb434539f9cca1ce4da.html
http://php.net
http://blog.csdn.net/wzhwho/article/details/6949297
http://blog.csdn.net/sbsujjbcy/article/details/42806865

0 0