用C開發PHP擴張初探

來源:互聯網
上載者:User
用C開發PHP擴充初探

學習PHP快2年了,對於PHP的有些東西還沒有弄透,今天趁著周末學習了一下如何用C語言開發PHP擴充

函數功能:php裡面的整數是有符號數,其內部實現其實就是long,不是unsigned long。對於32位機器來說,php最大能表示的整數就是2^31-1了,一般在應用中碰到大於2^31-1而小於2^32的數就只能用字串來表示了。對於mixed int_ext(string in)來說,如果字串in表示的整數小於2^31-1,那麼就返回整數,如果大於就返回字串。

開發擴充步驟如下:(首先需要下載php的源碼,這裡下載的是php-5.3.14)

1,建立擴充骨架

cd php-5.3.14/ext./ext_skel --extname=int_ext

2,修改編譯參數

cd php-5.3.14/ext/int_extvi config.m4去掉 PHP_ARG_ENABLE(int_ext, whether to enable int_ext support 和
[ --enable-int_ext Enable int_ext support]) 兩行前面的dnl 修改後為:

1. dnl Otherwise use enable: 2. PHP_ARG_ENABLE(int_ext, whether to enable int_ext support, 3. dnl Make sure that the comment is aligned: 4. [ --enable-int_ext Enable int_ext support])

3,編寫C代碼

cd php-5.3.14/ext/int_extvi php_int_ext.h#在 PHP_FUNCTION(confirm_int_ext_compiled); 後面新增一行 PHP_FUNCTION(int_ext);cd php-5.3.14/ext/int_extvi int_ext.c#在PHP_FE(confirm_int_ext_compiled, NULL) 後面添加 PHP_FE(int_ext, NULL)添加後為:1. zend_function_entry int_ext_functions[] = { 2.PHP_FE(confirm_int_ext_compiled, NULL) /* For testing, remove later. */ 3.PHP_FE(int_ext, NULL) /* For testing, remove later. */ 4.{NULL, NULL, NULL} /* Must be the last line in int_ext_functions[] */ 5. };

核心代碼:

PHP_FUNCTION(int_ext){ char * str = NULL; int str_len; int argc = ZEND_NUM_ARGS(); if(zend_parse_parameters(argc TSRMLS_CC,"s",&str,&str_len) == FAILURE) return ; char * result; int result_length = str_len; result = (char *) emalloc(result_length + 1); memcpy(result,str,result_length); unsigned long result_num = strtoul(result, NULL, 10); int sizeoflong sizeof(long); unsigned long max_long = 1 << (sizeoflong * 8 -1); if(result_num < max_long) { RETURN_LONG(result_num); } else { RESULT_STRINGL(result, result_length, 0); }}

4,編譯

cd php-5.3.14/ext/int_ext/usr/local/php/bin/pphpize./configure --with-php-config=/usr/local/php/bin/php-configmake make install

此時會產生一個so檔案: /usr/local/php/lib/php/extensions/no-debug-non-zts-20060613/int_ext.so

修改php.ini 添加擴充extension_dir = "/usr/local/php/lib/php/extensions/no-debug-non-zts-20060613/"

[int_ext]

extension = int_ext.so

5,測試

$a = int_ext("12345678900");var_dump($a);$a = int_ext("123456789");var_dump($a);

結果輸出:

string(11) "12345678900"int(123456789)






  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.