Search code examples
cprologffiinteger-arithmeticsicstus-prolog

Passing arbitrary-sized integers from Prolog to C


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?


Solution

  • 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);