swig扩展php(一)

同事拿C写了个东东,PHP不能直接用,便问他可否写个扩展,他于是提到SWIG,我想来惭愧,我写过的几个扩展,全部用的是PHP源码包中自带的ext_skel,于是开始学习了下SWIG。

swig是个好东东,可以把C包装成各种扩展,java/perl/python,详情可参见swig官网 http://www.swig.org/,可下载其最新版本,安装也非常简单,解压,./configure && make && makeinstall,有手就会。但教程中,只举例了java/perl等等,未发现PHP的影子,但根据其介绍,扩展php肯定是不成问题的,于是继续搜索,终于依靠我浅薄的C知识加上官网手册,用swig生成了PHP的扩展。

具体步骤:

1、先写个c文件,example.c

 /* File : example.c */



 



 #include <time.h>



 double My_variable = 3.0;



 



 int fact(int n) {



     if (n <= 1) return 1;



     else return n*fact(n-1);



 }



 



 int my_mod(int x, int y) {



     return (x%y);



 }



 	



 char *get_time()



 {



     time_t ltime;



     time(&ltime);



     return ctime(&ltime);



 }



 

2、写一个接口文件(interface file)投入到swig中。example.i

 /* example.i */



 %module example



 %{



 /* Put header files here or function declarations like below */



 extern double My_variable;



 extern int fact(int n);



 extern int my_mod(int x, int y);



 extern char *get_time();



 %}



 



 extern double My_variable;



 extern int fact(int n);



 extern int my_mod(int x, int y);



 extern char *get_time();

 3、建立PHP模块

swig -php example.i

这时可以看到生成了example.php  example_wrap.c  php_example.h这三个文件,我们vim example.php,可以看到这里将c文件中定义的函数都转化成了class example的静态函数,而且,example.php会先判断是否已load了example.so以及根据不同的OS来动态的引入该so。example_warp.c是根据要建立的扩展语言的不同而变化的,这里都是PHP和zend的一些宏

gcc -fpic -c example.c

生成了example.o,PICPosition-IndependentCode的缩写,因为动态链接库就是为了实现位置无关,所以需要使用-fPIC.

gcc `php-config --includes` -fpic -c example_wrap.c

 

 生成了example_wrap.o.`php-config --includes`是把php依赖的头文件路径全部获取

gcc -shared *.o -o example.so -I/usr/local/share

生成了example.so

cp example.so `php-config --extension-dir`

php的扩展路径中就会有该so了

4使用该扩展

方法1:

vim code.php

<?php
include "example.php";
echo example::get_time();
?>

注意:现在这个example.php派上用场了。然后再php code.php,怎么样,看见当前时间了吗?

方法2:

<?php

dl("example.so");

echo get_time();

?>

发布了30 篇原创文章 · 获赞 3 · 访问量 11万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章