How to store a term between C function calls in a foreign library

Hi,
I have a foreign C library and I have a predicate implemented in C that receives a term that should be stored (for example in a global variable) for further C functions to use it.
I have declared a global variable

term_t arg;

and I have a function

static foreign_t f1(term_t t1)
{
  arg=PL_copy_term_ref(t1);
}

I would another function to do something with the stored term

static foreign_t f2()
{
   do something with arg
}

However, this does not work. Should I serialize the term to a string, store the string and deserialize in f2?
How to serialize a term?

Thanks
Fabrizio

Perhaps PL_record() and PL_recorded() do what you want.
https://www.swi-prolog.org/pldoc/man?CAPI=PL_record

1 Like

In 2013, I was working on Qt ‘porting’ of swipl-win, and Jan explained the necessity to serialize terms to exchange terms between threads:
(from PREDICATE.h)

...   
    if ( PL_get_wchars(t.C_, NULL, &s, CVT_WRITEQ|BUF_RING) )
      return QString::fromWCharArray(s);
...

I could be wrong, but today, after the UTF-8 interface enhancements, I would first check how PL_get_chars performs…

You indeed need to serialize, but at @peter.ludemann suggested, PL_record() and PL_recorded() are a better choice. They are both faster and cover edge cases such as cyclic terms, internal sharing in terms and attributes.

If you do need to serialize (e.g., PL_record() doesn’t work for you), see library(fastrw), or PL_record_external().