1

I'm new to Zig and wanted to use the cImport to call out to the GNU Multiprecision library GMP. I got this to work but it feels awkward because Zig apparently doesn't cast from arrays to pointers by default and GMP uses this approach to pass by reference. Is there a cleaner approach than mine? Are there existing examples of Zig calling GMP?

const gmp = @cImport({
    @cInclude("gmp.h");
});

pub fn main() void {
    var x: gmp.mpz_t = undefined;
    gmp.mpz_init(&x[0]);
    gmp.mpz_set_ui(&x[0], 7);
    gmp.mpz_mul(&x[0], &x[0], &x[0]);
    _ = gmp.gmp_printf("%Zd\n", x);
}

1 Answers1

1

You should be able to drop the [0]:

const gmp = @cImport({
    @cInclude("gmp.h");
});

pub fn main() void {
    var x: gmp.mpz_t = undefined;
    gmp.mpz_init(&x);
    gmp.mpz_set_ui(&x, 7);
    gmp.mpz_mul(&x, &x, &x);
    _ = gmp.gmp_printf("%Zd\n", x);
}
daurnimator
  • 4,091
  • 18
  • 34
  • Thanks, that's cleaner. I hadn't fully appreciated the difference from C where &array would return a double pointer. – Alastair1729 Jun 09 '22 at 20:14