歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> PHP的SO擴展編程入門

PHP的SO擴展編程入門

日期:2017/3/1 9:55:44   编辑:Linux編程

獲取PHP源代碼
http://www.php.net/downloads.php#v5

解壓縮源代碼包

$ cd php-5.2.5/ext
建立擴展函數原型文件,下面會用到
gedit tsing.proto
輸入函數原型
string say_hello(string str_name)
保存並退出gedit

生成擴展
$ ./ext_skel --extname=tsing --proto=tsing.proto
ext_sket 顧名思義是生成擴展模塊的基本骨架,tsing 為擴展模塊名稱,執行後將在ext目錄下建立相應名稱的目錄

$ cd tsing

修改文件config.m4
#gedit ./ext/my_so_name/config.m4
去掉以下幾行代碼注釋標記"dnl"
PHP_ARG_WITH(tsing, for tsing support,
Make sure that the comment is aligned:
[ --with-tsing Include tsing support])
或如下幾行的注釋標記
PHP_ARG_ENABLE(tsing, whether to enable test support,
Make sure that the comment is aligned:
[ --enable-tsing Enable test support])
這幾行是說明PHP編譯時加載SO模塊的方式 with-tsing 或是 enable-tsing
with-tsing 表示需要第三方庫,enable-tsing 表示不需要第三方庫。

#gedit ./ext/tsing/tsing.c
在第43行看到say_hello函數自動在頭部已經注冊
/* {{{ tsing_functions[]
*
* Every user visible function must have an entry in tsing_functions[].
*/
zend_function_entry tsing_functions[] = {
PHP_FE(confirm_tsing_compiled, NULL) /* For testing, remove later. */
PHP_FE(say_hello, NULL)
{NULL, NULL, NULL} /* Must be the last line in tsing_functions[] */
};
/* }}} */
在第177行可以看到在原型文件tsing.proto中定義的函數已經在tsing.c中生成了代碼skel
/* {{{ proto string say_hello(string str_name)
*/
PHP_FUNCTION(say_hello)
{
char *str_name = NULL;
int argc = ZEND_NUM_ARGS();
int str_name_len;
if (zend_parse_parameters(argc TSRMLS_CC, "s", &str_name, &str_name_len) == FAILURE)
return;
php_error(E_WARNING, "say_hello: not yet implemented");
}
/* }}} */
如下注釋掉第186行代碼
// php_error(E_WARNING, "say_hello: not yet implemented");
添加
php_printf("Hello,".str_name.";");
保存並退出gedit

查看頭文件
#gedit ./ext/tsing/php_tsing.h
發現在44行已經添加好了say_hello函數的原型
PHP_FUNCTION(say_hello);
保存並退出gedit

配置
有兩種方式進行配置
方法A
#./buildconf --force (加上force參數是避免您使用的php版本為release版本)
#./configure --disable-all --with-tsing=shared --with-apxs2=/usr/sbin/apxs --prefix=/usr/lib/php/modules
上面命令中,--disable-all是為了加快編譯速度而使用的,減少php默認要編譯的模塊數量。 --with-tsing=shared為了編譯後能直接生產.so文件, --with-apxs2=/usr/sbin/apxs是根據您服務器上apache安裝具體路徑和版本來確定的

方法B
找到php安裝目錄裡的 bin/phpize
$ /usr/bin/phpize
在 tsing 目錄下生成configure文件
確定php-config文件和apxs安裝位置,運行configure
./configure --with-php-config=/usr/bin/php-config --enable-tsing=shared --with-apxs2=/usr/sbin/apxs --prefix=/usr/lib/php/modules

編譯
#make

安裝
#gedit /etc/php.d/tsing.ini 加入extension=tsing.so

#make install 或 #cp ./ext/tsing/.libs/tsing.so /usr/lib/php/ext/

重啟APACHE

查看phpinfo()函數結果,確認存在tsing一欄

如此在調用文件中可以直接使用動態擴展的函數
echo say_hello("Tsing");
輸出
Hello,Tsing;

Copyright © Linux教程網 All Rights Reserved