原文
http://hi.baidu.com/thinkinginlamp/item/e5b89c23657b520977272c7f
前提條件是你的系統已經安裝好了apache和php,並且要有一份對應的php源代碼,這些都不是難事。
-----------------------------------------------------------------------------------------------
進入php源代碼目錄,然後看看操作過程(這裏假設我們要做一個名爲test的擴展):
cd ./ext
./ext_skel --extname=test
cd ./test
vi config.m4
這裏要對config.m4文件做一些修改:
dnl PHP_ARG_ENABLE(test, whether to enable test support,
dnl Make sure that the comment is aligned:
dnl [ --enable-test Enable test support])
去掉上面三行的dnl,使之變爲
PHP_ARG_ENABLE(test, whether to enable test support,
Make sure that the comment is aligned:
[ --enable-test Enable test support])
dnl在這裏是起到註釋的作用,當然你也可以去掉下面三句前面的dnl
dnl PHP_ARG_WITH(test, for test support,
dnl Make sure that the comment is aligned:
dnl [ --with-test Include test support])
這中間的區別就在於編譯時是使用enable-test還是with-test,前者意味着不需要第三方庫,後者正好相反,這裏我們選擇enable-test方式。
vi test.c
我們還可以通過修改test.c文件來增加或者的功能,這裏我們是演示目的,就不修改這個文件了。
/usr/local/bin/phpize
執行這一步的目的是根據config.m4文件的內容生成configure文件
./configure --enable-test
make
這時,在./ext/test/modules目錄就應該已經生成了test.so擴展模塊了,怎麼樣,很簡單吧。
make install
會自動把生成的test.so模塊拷貝到php認爲正確的擴展目錄,我測試的時候此目錄爲
/usr/local/lib/php/extensions/no-debug-non-zts-20060613/
no-debug-non-zts-20060613部分可能有差異,具體依賴與php的版本和編譯選項。
如果你不詳把擴展放在上面所示的目錄中,可以
vi /usr/local/lib/php.ini
修改extension_dir選項爲你的擴展目錄名,並把test.so複製到此目錄中
然後執行擴展目錄中的test.php文件(此文件是自動生成的)
/usr/local/bin/php -f test.php
會發現如下字樣:
Functions available in the test extension:
confirm_test_compiled
Congratulations! You have successfully modified ext/test/config.m4. Module test is now compiled into PHP.
----------------------------------------------------------------------------------------------
test.php文件中使用dl函數來動態加載test.so擴展,如果你想讓php自動加載此擴展,只要進行如下操作即可:
vi /usr/local/lib/php.ini 加入extension=test.so
/usr/local/apache2/bin/apachectl restart
此時,如果你瀏覽phpinfo(),會發現test相應的擴展信息。
如果你使用命令行,那麼通過下面命令也能看到:/usr/local/bin/php -m
----------------------------------------------------------------------------------------------
我們編寫的test擴展成功了,當然,目前它還沒有任何有用的功能,呵呵。