PHP-CPP 返回一个字符串导致 strlen 而不是纯字符串

问题描述

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

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,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 在 PHP 中;调用函数,如下所示:

$result = $math->some_pow(100,0.84);

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

解决方法

根据文档(并将其与常规 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 返回打印到标准输出的字符数。

如果要将文本作为字符串获取,而不是将其打印到标准输出,则需要使用以下内容:

— 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. 
,

结果是正确的。您正在返回 mpfr_printf() 的结果。从手册: 返回值是字符串中写入的字符数,不包括空终止符,如果发生错误,则返回负值,在这种情况下,str的内容未定义。

在此处阅读更多信息: http://cs.swan.ac.uk/~csoliver/ok-sat-library/internet_html/doc/doc/Mpfr/3.0.0/mpfr.html/Formatted-Output-Functions.html

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...