某個功能被編譯到so檔案中,那麼如何通過php來調用它?一個方法是寫一個php模組(php
extension),在php中調用該模組內的函數,再通過該模組來調用so中的函數。下面做一個簡單的例子,使用的作業系統是RHEL5。
首先做一個簡單的so檔案:
/** * hello.c * To compile, use following commands: * gcc -O -c -fPIC -o hello.o hello.c * gcc -shared -o libhello.so hello.o */int hello_add(int a, int b){ return a + b;}
然後將它編譯成.so檔案並放到系統中:
$ gcc -O -c -fPIC -o hello.o hello.c$ gcc -shared -o libhello.so hello.o$ su# echo /usr/local/lib > /etc/ld.so.conf.d/local.conf# cp libhello.so /usr/local/lib# /sbin/ldconfig
寫段小程式來驗證其正確性:
/** * hellotest.c * To compile, use following commands: * gcc -o hellotest -lhello hellotest.c */#i nclude <stdio.h>int main(){ int a = 3, b = 4; printf("%d + %d = %d/n", a, b, hello_add(a,b)); return 0;}
編譯並執行:
$ 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 。)
16: PHP_ARG_ENABLE(hello, whether to enable hello support,17: dnl Make sure that the comment is aligned:18: [ --enable-hello Enable hello support])
然後執行 phpize 程式,產生configure指令碼:
$ phpize
然後開啟 php_hello.h,在 PHP_FUNCTION(confirm_hello_compiled); 之下加入函式宣告:
PHP_FUNCTION(confirm_hello_compiled); /* For testing, remove later. */PHP_FUNCTION(hello_add);
開啟 hello.c,在 PHP_FE(confirm_hello_compiled, NULL) 下方加入以下內容。
zend_function_entry hello_functions[] = { PHP_FE(confirm_hello_compiled, NULL) /* For testing, remove later. */ PHP_FE(hello_add, NULL) /* For testing, remove later. */ {NULL, NULL, NULL} /* Must be the last line in hello_functions[] */};
然後在 hello.c 的最末尾書寫hello_add函數的內容:
PHP_FUNCTION(hello_add){ long int a, b; long int result; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ll", &a, &b) == FAILURE) { return; } result = hello_add(a, b); RETURN_LONG(result);}
儲存退出,編譯並安裝:
$ ./configure$ make LDFLAGS=-lhello$ su# cp modules/hello.so /usr/lib/php/modules
然後在 /var/www/html 下建立一個 hello.php 檔案,內容如下:
<?php dl("hello.so"); echo hello_add(3, 4);?>
然後在瀏覽器中開啟hello.php檔案,如果顯示7,則說明函數調用成功了。