首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >返回字符串的PHP-CPP将导致strlen而不是普通字符串。

返回字符串的PHP-CPP将导致strlen而不是普通字符串。
EN

Stack Overflow用户
提问于 2021-04-27 11:44:58
回答 2查看 83关注 0票数 0

因此,我在php-cpp的帮助下编写了一个小小的扩展。在这个函数中,我只是简单地计算pow,它工作得非常好。计算结果后,从函数返回字符串。当我在php中调用这个扩展函数时,我收到一个整数,它包含原始字符串的strlen,而不是我的字符串:

代码语言:javascript
复制
Php::Value Math::some_pow(Php::Parameters &params)
{
    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输出:

代码语言:javascript
复制
base=1e+02  exponent=8.3999999999999996891375531049561686813831329345703125e-01
Result=4.7875e+01

因此,函数本身应该返回以下内容:Result=4.7875e+01;调用函数,如下所示:

代码语言:javascript
复制
$result = $math->some_pow(100, 0.84);

通过var_dump($result);的输出显示了17 ->的"Result=4.7875e+01“

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-04-27 11:51:00

根据docs (并将其与常规printf进行比较),您的函数按预期工作:

代码语言:javascript
复制
— 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,则需要使用以下内容:

代码语言:javascript
复制
— 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. 
票数 1
EN

Stack Overflow用户

发布于 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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67282426

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档