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

99 views Asked by At

So i wrote a little extension with the help of php-cpp. In this function, i just simply calculate the pow, which works perfectly fine. After calculating the result, i return the string from the function. When i call this extensions function in php, i receive an integer which contains the strlen of my original string, instead of my string:

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;
}

The mpfr_printf output, to verify that everything inside the function works well:

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

So the function itself is supposed to return the following: Result=4.7875e+01 In PHP; calling the function, which looks like this:

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

Output via var_dump($result); shows 17 -> the strlen of "Result=4.7875e+01"

2

There are 2 answers

2
Dan M. On BEST ANSWER

According to the docs (and comparing it to regular printf), your function works as expected:

— 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 returns the number of characters printed to the stdout.

If you want to get the text as a string, instead of printing it to stdout, you need to use something like:

— 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. 
0
StureS On

The result is correct. You are returning the result of mpfr_printf(). From the manual: The return value is the number of characters written in the string, excluding the null-terminator, or a negative value if an error occurred, in which case the contents of str are undefined.

Read more here: http://cs.swan.ac.uk/~csoliver/ok-sat-library/internet_html/doc/doc/Mpfr/3.0.0/mpfr.html/Formatted-Output-Functions.html