Search code examples
csicstus-prologclpfd

Create prolog list from C


I have a C-program as frontend to a Sicstus Prolog runtime. And I'm trying to create a list in C, fill it out and pass to the Prolog runtime. I have had a look at the C-library, but I don't find any information of how this should be done. I guess it is not a single function call that does this, but rather a combination(?)

I also see that there are several function-calls in the C-library that are related to this like (SP_put_list(), SP_put_list_codes(), SP_put_list_n_bytes(), SP_put_list_n_codes() )

The list I want to create is the list of opions to pass to labeling/2 like [leftmost,step,up,all], but I want to create and fill out this list at runtime, and pass it over to Sicstus Prolog.


Solution

  • You can use SP_cons_list() to create a new list cell from its head and tail. That is,

    SP_term_ref my_list = SP_new_term_ref();
    if (!SP_cons_list(my_list, head, tail)) { goto error_handling; }
    

    corresponds roughly to the Prolog code:

    My_List = [Head|Tail]
    

    If speed is not very important it may be simplest to use SP_read_from_string(), e.g.:

    SP_term_ref my_list = SP_new_term_ref();
    if (!SP_read_from_string(my_list, "[leftmost,step,up,all].", NULL)) {
       goto error_handling;
    }
    // my_list is [leftmost,step,up,all] here.
    

    Of course, it is even easier to do as much as possible of this in Prolog.