在php擴充中,時常需要接受php類型的數組作為參數,php數組的參數都是zval類型的,並不適合在擴充中方便的使用,一般都要提前轉換成c或cpp中的資料類型。首先看一個轉換的例子:
void convert_to_vector(const zval * vals, vector<string> &valList) ...{
// create the list to write
HashPosition pos;
zval **z_val = NULL;
string value;
zend_hash_internal_pointer_reset_ex( Z_ARRVAL_P( vals ), &pos );
while ( zend_hash_get_current_data_ex( Z_ARRVAL_P( vals ), (void **)&z_val, &pos ) == SUCCESS ) ...{
convert_to_string_ex( z_val );
value = Z_STRVAL_PP(z_val);
valList.push_back(value);
zend_hash_move_forward_ex( Z_ARRVAL_P( vals ), &pos );
}
}
上述列子是把php的數群組轉換成vector<string>的類型。HashPosition 是一個指標,通過zend_hash_internal_pointer_reset_ex( Z_ARRVAL_P( vals ), &pos );方法使得pos指向zval數組的第一個元素,然後通過while迴圈中的zend_hash_get_current_data_ex( Z_ARRVAL_P( vals ), (void **)&z_val, &pos ) 方法取得pos所指位置的元素值,儲存在z_val指標中。
convert_to_string_ex( z_val ),轉換z_val中包含的實際資料為字串,value = Z_STRVAL_PP(z_val) 則獲得此字串的值,然後push_back到valList中。zend_hash_move_forward_ex( Z_ARRVAL_P( vals ), &pos );則移動pos到下一個元素位置。