Passing arbitrary-sized integers from Prolog to C
Asked Answered
D

1

25

Right now, I'm learning how to interface SICStus Prolog with C code.

I would like to have/use/see a C implementation of "Hamming weight" of arbitrary-sized integers in SICStus Prolog version 4.

It seems to me that I need C functions for testing term types (SP_is_integer) and C functions for accessing Prolog terms (SP_get_integer, SP_get_integer_bytes).

However, I'm not sure how to use SP_get_integer_bytes in a portable, robust fashion. Could you please point me to some well-crafted solid C code doing just that?

Draconic answered 3/3, 2015 at 12:39 Comment(1)
SP_get_integer_bytes() is for arbitrary precision integers.Wavelength
W
14

Use it something like this:

SP_term_ref tr = ... some term ...
int native = 0; // want portable, little endian
size_t buf_size = 0;

if (!SP_get_integer_bytes(tr, NULL, &buf_size, native)
    // if buf_size was updated, then there was not really an error
    && buf_size == 0)
{
    // Something wrong (e.g., not an integer)
    return ERROR;
}

// here buf_size > 0
void *buffer = SP_malloc(buf_size);

if (buffer == NULL)
{
    return ERROR;
}

if (!SP_get_integer_bytes(tr, buffer, &buf_size, native))
{
    // Something wrong. This would be surprising here
    error();
}

// Here buffer contains buf_size bytes, in
// twos-complement, with the least significant bytes at lowest index.
// ... do something with buffer ...

// finally clean up
SP_free(buffer);
Wavelength answered 3/3, 2015 at 16:2 Comment(1)
This works with any integer. This works with any buffer (e.g. you could use a static buffer that is usually large enough, and then allocate a dynamic buffer when the integer is too large to fit in the static buffer).Wavelength

© 2022 - 2024 — McMap. All rights reserved.