繁体   English   中英

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

[英]PHP-CPP returning a string results in the strlen instead of plain string

所以我在 php-cpp 的帮助下写了一个小扩展。 在这个 function 中,我只是简单地计算 pow,它工作得很好。 计算结果后,我从 function 返回字符串。 当我在 php 中调用此扩展 function 时,我收到一个 integer,其中包含我的原始字符串的 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, exponent, GMP_RNDN);

    char data[255];
    mpfr_snprintf(data, 254, "%.20Ff", result);

    return data;
}

mpfr_printf output,以验证 function 内的所有内容是否正常工作:

base=1e+02  exponent=8.3999999999999996891375531049561686813831329345703125e-01
Result=4.7875e+01

所以 function 本身应该返回以下内容: Result=4.7875e+01 In PHP; 调用 function,如下所示:

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

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

根据文档(并将其与常规 printf 进行比较),您的 function 可以按预期工作:

— 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/~csolive/ok-sat-library/internet_html/doc/doc/Mpfr/3.0.0/mpfr.html/Formatted-Output-Functions.ZFC35FDC70D5FC69D269883A822C7A53E

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM