PHP扩展:第三个程序

来源:互联网 发布:mac退出到桌面快捷键 编辑:程序博客网 时间:2024/05/01 18:00

这是一个关于数学多项式运算的php扩展程序,综合了php扩展开发时多种数据格式引入,希望对大家有所帮助。

1.多项式相乘

这个函数表示的意思是

计算多项式

P(x) = 2*x^6-5*x^5+3*x^4+x^3-7*x^2+7*x-20

求在 x = 1,2,3,4,5,6处的函数值。


1).在php_phpext.h文件中新建一个函数php_multiterm

PHP_FUNCTION(php_multiterm)

2).在phpext.cpp文件中创建一个函数php_multiterm

添加PHP_FE(php_multiterm, NULL)


在phpext.cpp中添加

PHP_FUNCTION(php_multiterm){    zval *values, *keys;    HashPosition pos_values, pos_keys;    zval **entry_keys, **entry_values;    zval entry_nkeys,entry_nvalues;    int num_keys, num_values;    double r,i;    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "aa", &keys, &values) == FAILURE) {        return;        }    num_keys = zend_hash_num_elements(Z_ARRVAL_P(keys));    num_values = zend_hash_num_elements(Z_ARRVAL_P(values));    array_init_size(return_value, num_values);    if (!num_values) {        return;        }    array_init(return_value);    for (zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(values), &pos_values);        zend_hash_get_current_data_ex(Z_ARRVAL_P(values), (void **)&entry_values, &pos_values) == SUCCESS;        zend_hash_move_forward_ex(Z_ARRVAL_P(values), &pos_values))    {        entry_nvalues = **entry_values;        zval_copy_ctor(&entry_nvalues);        convert_scalar_to_number(&entry_nvalues TSRMLS_CC);        zend_hash_internal_pointer_end_ex(Z_ARRVAL_P(keys), &pos_keys);        zend_hash_get_current_data_ex(Z_ARRVAL_P(keys), (void **)&entry_keys, &pos_keys) == SUCCESS;        entry_nkeys = **entry_keys;        zval_copy_ctor(&entry_nkeys);        convert_scalar_to_number(&entry_nkeys TSRMLS_CC);        r = (double)Z_LVAL(entry_nkeys);        i = (double)Z_LVAL(entry_nkeys);        for (zend_hash_internal_pointer_end_ex(Z_ARRVAL_P(keys), &pos_keys);            zend_hash_get_current_data_ex(Z_ARRVAL_P(keys), (void **)&entry_keys, &pos_keys) == SUCCESS;            zend_hash_move_backwards_ex(Z_ARRVAL_P(keys), &pos_keys)        {            entry_nkeys = **entry_keys;            zval_copy_ctor(&entry_nkeys);            convert_scalar_to_number(&entry_nkeys TSRMLS_CC);            r = r*(double)Z_LVAL(entry_nvalues)+(double)Z_LVAL(entry_nkeys);            }                        for(int j = 0;j < num_keys;j++)        {            i *= (double)Z_LVAL(entry_nvalues);           }        r = r - i;        add_index_double(return_value, (double)Z_LVAL(entry_nvalues), r);        }}



这是多项式求值函数的代码

3).编译

/usr/local/php/bin/phpize  扩展

./configure --with-php-config=/usr/local/php/bin/php-config

make && make install 编译

重启apache

4).新建php文件内容如下



访问localhost就能看到打印的内容!


恭喜你,又进步了!


1 0