将任意大小的整数从 Prolog 传递到 C

Passing arbitrary-sized integers from Prolog to C

现在,我正在学习如何使用 C 代码连接 SICStus Prolog。

我想 have/use/see SICStus Prolog 版本 4 中 "Hamming weight" 任意大小整数的 C 实现。

在我看来,我需要 C 函数来测试术语类型 (SP_is_integer) 和 C 函数来访问 Prolog 术语 (SP_get_integer, SP_get_integer_bytes)。

但是,我不确定如何以便携、稳健的方式使用 SP_get_integer_bytes。你能给我指出一些精心设计的可靠 C 代码吗?

像这样使用它:

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