PHP擴展開發之整型參數傳遞

 實現一個加法函數,傳入2個參數,計算相加的和:
 
 1.創建一個新的擴展
	./ext_skel --extname=hello
	
  2.vi config.m4   去掉以下3行行首的dnl
          PHP_ARG_ENABLE(hello, whether to enable strive support,
          Make sure that the comment is aligned:
          [  --enable-hello           Enable strive support]) 
            
 3,編寫代碼 
	1.vi hello.c
	
	2.#添加下面的代碼
    	    ZEND_BEGIN_ARG_INFO(addition_arginfo, 0)
            ZEND_ARG_INFO(0, num1)
            ZEND_ARG_INFO(0, num2)
    	    ZEND_END_ARG_INFO()

	PHP_FUNCTION(addition) {
    	    long num1,num2;
    	    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ll", &num1, &num2) == FAILURE) {
        	   return;
    	    }
    	    RETURN_LONG(num1+num2);
	 }
	
	
	3.在數組中添加函數名:
	  const zend_function_entry  hello_functions[] = {
	          PHP_FE(addition, NULL)           /* addition function */
	}
	
	
	
解釋:
    這裏創建的拓展名爲hello,所以需要編輯hello.c文件,在裏面加上相應的函數。這裏加上了addition
    函數,主要功能是實現兩個參數的相加。定義了2個參數,num1與num2。
    ZEND_BEGIN_ARG_INFO  :開始參數塊定義
    ZEND_END_ARG_INFO      :結束參數塊定義
    ZEND_ARG_INFO      :聲明普通參數 
    PHP_FUNCTION(addition) :這裏是爲擴展添加具體的函數,函數名爲(addition)
    函數內定義了兩個long類型的變量,這裏定義的變量與上面參數塊中定義的對應。 
    RETURN_LONG:表示返回一個long類型的值,
    
    
 4.編譯安裝擴展,
       phpize
       ./configure --with-php-config=php_conf_dir
       make && make install
       vi php.ini  
       extension=strive.so       
       reload php-fpm 
 
 5.測試addition函數是否可用:
             php -r 'echo addition(10,40);' 
         
    
    
    	
		


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章