Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing arbitrary-sized integers from Prolog to C

Tags:

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?

like image 287
repeat Avatar asked Mar 03 '15 12:03

repeat


1 Answers

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); 
like image 65
Per Mildner Avatar answered Sep 20 '22 17:09

Per Mildner