17.4.5 Managing MPFR and GMP Values

MPFR and GMP values are different from string values, where you can “take ownership” of the value simply by assigning pointers. For example:

char *p = gawk_malloc(42);      p ``owns'' the memory
char *q = p;
p = NULL;                       now q ``owns'' it

MPFR and GMP objects are indeed allocated on the stack or dynamically, but the MPFR and GMP libraries treat these objects as values, the same way that you would pass an int or a double by value. There is no way to “transfer ownership” of MPFR and GMP objects.

The final results of an MPFR or GMP calculation should be passed back to gawk, by value, as you would a string or a double. gawk will take care of freeing the storage.

Thus, code in an extension should look like this:

mpz_t part1, part2, answer;             declare local values

mpz_set_si(part1, 21);                  do some computations
mpz_set_si(part2, 21);
mpz_add(answer, part1, part2);
...
/* assume that result is a parameter of type (awk_value_t *). */
make_number_mpz(answer, & result);      set it with final GMP value

mpz_clear(part1);                       release intermediate values
mpz_clear(part2);

return result;                          value in answer managed by gawk