9.4.7 Miscellaneous

A dynamic foreign resource that is used by multiple SICStus run-times in the same process may need to maintain a global state that is kept separate for each SICStus run-time. Each SICStus run-time maintains a location (containing a void*) for each foreign resource. A foreign resource can then access this location to store any data that is specific to the calling SICStus run-time.

     void **SP_foreign_stash(void)

You can use SP_foreign_stash() to get access to a location, initially set to NULL, where the foreign resource can store a void*. Typically this would be a pointer to a C struct that holds all information that need to be stored in global variables. This struct can be allocated and initialized by the foreign resource init function, it should be deallocated by the foreign resource deinit function.

SP_foreign_stash() is only available for use in dynamic foreign resources. The value returned by SP_foreign_stash() is only valid until the next SICStus API call. The correct way to initialize the location pointed at by SP_foreign_stash() is therefore:

     struct my_state {...};
     
     init_my_foreign_resource(...)
     {
        struct my_state *p = SP_malloc(sizeof(struct my_state));
        (*SP_foreign_stash()) = (void*)p;
     }

The following example is incorrect; SP_malloc() may be called between the time SP_foreign_stash() is called and the time its return value is used:

     /* WRONG */
     (*SP_foreign_stash()) = SP_malloc(sizeof(struct my_state));

SP_foreign_stash() is currently a C macro, not a function. You should not rely on this.