Passing arbitrary-sized integers from Prolog to C

独自空忆成欢 提交于 2020-01-03 07:20:29

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/28832027/passing-arbitrary-sized-integers-from-prolog-to-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!