本篇文章給大家?guī)淼膬?nèi)容是介紹如何使用C語言給PHP寫擴展,,有一定的參考價值,有需要的朋友可以參考一下,希望對你有所幫助。
1、在php源碼路徑的ext文件夾下,新建一個extend_test.def文件,編輯文件內(nèi)容為:
string my_test_function(string str,int n)
2、在當前目錄執(zhí)行
./ext_skel --extname=extend_test --proto=extend_test.def
其中,extname是擴展的名,proto是剛創(chuàng)建的文件,也可以用全路徑
3、在當前目錄下會生成extend_test文件夾,編輯extend_test文件夾下的config.m4
去掉一下三行的dnl的注釋
PHP_ARG_ENABLE(extend_test, whether to enable extend_test support,
Make sure that the comment is aligned:
[ --enable-extend_test Enable extend_test support])
4、編輯extend_test文件夾下的extend_test.c文件
找到以下方法并修改
- PHP_FUNCTION(my_test_function)
- {
- char *str = NULL;
- int argc = ZEND_NUM_ARGS();
- size_t str_len;
- zend_long n;
- char *result;
- char *ptr;
- zend_long result_length;
- if (zend_parse_parameters(argc TSRMLS_CC, "sl", &str, &str_len, &n) == FAILURE)
- return;
- result_length = str_len * n;
- result = (char *) emalloc(result_length + 1);
- ptr = result;
- while (n--) {
- memcpy(ptr, str, str_len);
- ptr += str_len;
- //Vevb.com
- }
- *ptr = '/0';
- RETURN_STRINGL(result, result_length);
- }
5、生成擴展:
在extend_test文件夾下,運行/home/php/bin/phpize(實際為phpize所在路徑)
然后運行./configure --with-php-config=/home/php/bin/php-config(實際為php-config所在路徑)
6、編譯安裝
make
make install
7、執(zhí)行完后會顯示擴展安裝到了哪個路徑下
然后修改php.ini增加擴展信息
extension=extend_test.so
8、測試擴展是否可用
新建test.php文件并將內(nèi)容編輯為
- echo my_test_function('a',5);
保存后用php運行,顯示出aaaaa表示擴展成功安裝
新聞熱點
疑難解答