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

时间:2015-03-03 12:39:14

标签: c prolog ffi integer-arithmetic sicstus-prolog

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

我想在SICStus Prolog版本4中使用/使用/查看任意大小的“汉明权重”的C实现。

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

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

1 个答案:

答案 0 :(得分:14)

使用类似这样的东西:

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