標籤:io 使用 ar strong for 檔案 資料 sp div
為什麼要用C擴充
C是靜態編譯的,執行效率比PHP代碼高很多。同樣的運算代碼,使用C來開發,效能會比PHP要提升數百倍。IO操作如CURL,因為耗時主要在IOWait上,C擴充沒有明顯優勢。
另外C擴充是在進程啟動時載入的,PHP代碼只能操作Request生命週期的資料,C擴充可操作的範圍更廣。
第一步
下載PHP的原始碼,如php-5.4.16。解壓後進入php-5.4.16\ext目錄。輸入 ./ext_skel –extname=myext,myext就是擴充的名稱,執行後產生myext目錄。
ext_skel是PHP官方提供的用於產生php擴充骨架代碼的工具。
cd myext。可以看到php_myext.h、myext.c、config.m4等幾個檔案。config.m4是AutoConf工具的設定檔,用來修改各種編譯選項。
第二步
修改config.m4,將
dnl PHP_ARG_WITH(myext, for myext support,dnl Make sure that the comment is aligned:dnl [ --with-myext Include myext support])
修改為
PHP_ARG_WITH(myext, for myext support,[ --with-myext Include myext support])
下邊還有一個 –enable-myext,是表示編譯到php核心中。with是作為動態連結程式庫載入的。
第三步
修改php_myext.h,看到PHP_FUNCTION(confirm_myext_compiled); 這裡就是擴充函式宣告部分,可以增加一行 PHP_FUNCTION(myext_helloworld); 表示聲明了一個myext_helloworld的擴充函數。
然後修改myext.c,這個是擴充函數的實現部分。
const zend_function_entry myext_functions[] = { PHP_FE(confirm_myext_compiled, NULL) /* For testing, remove later. */ PHP_FE(myext_helloworld, NULL) PHP_FE_END /* Must be the last line in myext_functions[] */};
這的代碼是將函數指標註冊到Zend引擎,增加一行PHP_FE(myext_helloworld, NULL)(後面不要帶分號)。
第四步
在myext.c末尾加myext_helloworld的執行代碼。
PHP_FUNCTION(myext_helloworld){ char *arg = NULL;int arg_len, len;char *strg;if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &arg, &arg_len) == FAILURE) {return;}php_printf("Hello World!\n");RETRUN_TRUE;}
zend_parse_parameters是用來接受PHP傳入的參數,RETURN_XXX宏是用來返回給PHP資料。
第五步
在myext目錄下依次執行phpize、./configure 、make、make install。然後修改php.ini加入extension=myext.so
執行php -r “myext_helloworld(‘test’);”,輸出hello world!
如何編寫一個PHP的C擴充