因此,我在php-cpp的帮助下编写了一个小小的扩展。在这个函数中,我只是简单地计算pow,它工作得非常好。计算结果后,从函数返回字符串。当我在php中调用这个扩展函数时,我收到一个整数,它包含原始字符串的strlen,而不是我的字符串:
Php::Value Math::some_pow(Php::Parameters ¶ms)
{
mpfr_t base, exponent, result;
mpfr_set_emin(mpfr_get_emin_min());
mpfr_init2(base, 256);
mpfr_init2(exponent, 256);
mpfr_init2(result, 10);
mpfr_set_str(base, params[0], 10, GMP_RNDN);
mpfr_set_d(exponent, params[1], GMP_RNDN);
mpfr_pow(result, base, exponent, GMP_RNDN);
char data[255];
mpfr_snprintf(data, 254, "%.20Ff", result);
return data;
}为了验证函数中的所有内容运行良好,mpfr_printf输出:
base=1e+02 exponent=8.3999999999999996891375531049561686813831329345703125e-01
Result=4.7875e+01因此,函数本身应该返回以下内容:Result=4.7875e+01;调用函数,如下所示:
$result = $math->some_pow(100, 0.84);通过var_dump($result);的输出显示了17 ->的"Result=4.7875e+01“
发布于 2021-04-27 11:51:00
根据docs (并将其与常规printf进行比较),您的函数按预期工作:
— Function: int mpfr_printf (const char *template, ...)
Print to stdout the optional arguments under the control of the template string template. Return the number of characters written or a negative value if an error occurred. mpfr_printf返回输出到标准输出的字符数。
如果要将文本作为字符串获取,而不是将其打印到stdout,则需要使用以下内容:
— Function: int mpfr_snprintf (char *buf, size_t n, const char *template, ...)
Form a null-terminated string corresponding to the optional arguments under the control of the template string template, and print it in buf. No overlap is permitted between buf and the other arguments. Return the number of characters written in the array buf not counting the terminating null character or a negative value if an error occurred. 发布于 2021-04-27 11:56:45
结果是正确的。您正在返回mpfr_printf()的结果。从手册中:返回值是在字符串中写入的字符数,不包括null-结束符,或者如果发生错误,则为负值,在这种情况下,str的内容是未定义的。
在这里阅读更多信息:http://cs.swan.ac.uk/~csoliver/ok-sat-library/internet_html/doc/doc/Mpfr/3.0.0/mpfr.html/Formatted-Output-Functions.html
https://stackoverflow.com/questions/67282426
复制相似问题