原作者charlee、原始連結http://tech.idv2.com/2007/07/06/use-local-so-in-php/
某個功能被編譯到so檔案中,那麼如何通過php來調用它。一個方法是寫一個php模組(php extension),在php中調用該模組內的函數,再通過該模組來調用so中的函數。下面做一個簡單的例子,使用的作業系統是Fedora Core 6。
首先做一個簡單的so檔案:
1 /**
2 * hello.c
3 * To compile, use following commands:
4 * gcc -O -c -fPIC -o hello.o hello.c
5 * gcc -shared -o libhello.so hello.o
6 */
7
8 int hello_add(int a, int b)
9 {
10 return a + b;
11 }
然後將它編譯成.so檔案並放到系統中:
1 ___FCKpd___1nbsp;gcc -O -c -fPIC -o hello.o hello.c
2 ___FCKpd___1nbsp;gcc -shared -o libhello.so hello.o
3 ___FCKpd___1nbsp;su
4 # echo /usr/local/lib > /etc/ld.so.conf.d/local.conf
5 # cp libhello.so /usr/local/lib
6 # /sbin/ldconfig
寫段小程式來驗證其正確性:
1/**//**
2 * hellotest.c
3 * To compile, use following commands:
4 * gcc -o hellotest -lhello hellotest.c
5 */
6 #include <stdio.h>
7 int main()
8 {
9 int a = 3, b = 4;
10 printf("%d + %d = %d/n", a, b, hello_add(a,b));
11 return 0;
12 } 編譯並執行:
$ gcc -o hellotest -lhello hellotest.c$ ./hellotest3 + 4 = 7
OK,下面我們來製作PHP模組。首先確保你安裝了 php-devel 包,沒有的話請自行從安裝光碟片上找。然後下載php原始碼。我使用的是php-5.2.3.tar.gz,解壓縮。
$ tar xzvf php-5.2.3.tar.gz$ cd php-5.2.3/ext
然後通過下面的命令建立一個名為 hello 的模組。
$ ./ext_skel --extname=hello
執行該命令之後它會提示你應當用什麼命令來編譯模組,可惜那是將模組整合到php內部的編譯方法。如果要編譯成可動態載入的 php_hello.so,方法要更為簡單。
$ cd hello
首先編輯 config.m4 檔案,去掉第16行和第18行的注釋(注釋符號為 dnl 。)
1 16: PHP_ARG_ENABLE(hello, whether to enable hello support,
2 17: dnl Make sure that the comment is aligned:
3 18: [ --enable-hello Enable hello support])
然後執行 phpize 程式,產生configure指令碼:
$ phpize
然後開啟 php_hello.h,在 PHP_FUNCTION(confirm_hello_compiled); 之下加入函式宣告:
1PHP_FUNCTION(confirm_hello_compiled); /**//* For testing, remove later. */
2 PHP_FUNCTION(hello_add); 開啟 hello.c,在 PHP_FE(confirm_hello_compiled, NULL) 下方加入以下內容。
1 zend_function_entry hello_functions[] = {
2 PHP_FE(confirm_hello_compiled, NULL) /**//* For testing, remove later. */
3 PHP_FE(hello_add, NULL) /**//* For testing, remove later. */
4 {NULL, NULL, NULL} /**//* Must be the last line in hello_functions[] */
5 };
然後在 hello.c 的最末尾書寫hello_add函數的內容: