Init and Deinit Functions

An init function and/or a deinit function can be declared by foreign_resource/2. If this is the case, these functions should have the prototype:

void FunctionName (int when)

The init function is called by load_foreign_resource/1 after the resource has been loaded and the interfaced predicates have been installed. If the init function fails (using SP_fail()) or raises an exception (using SP_raise_exception()), the failure or exception is propagated by load_foreign_resource/1 and the foreign resource is unloaded (without calling any deinit function). However, using SP_fail() is not recommended, and operations that may require SP_raise_exception() are probably better done in an init function that is called explicitly after the foreign resource has been loaded.

The deinit function is called by unload_foreign_resource/1 before the interfaced predicates have been uninstalled and the resource has been unloaded. If the deinit function fails or raises an exception, the failure or exception is propagated by unload_foreign_resource/1, but the foreign resource is still unloaded. However, neither SP_fail() nor SP_raise_exception() should be called in a deinit function. Complex deinitialization should be done in an explicitly called deinit function instead.

The init and deinit functions may use the C-interface to call Prolog etc.

Foreign resources are unloaded before saving states, and reloaded afterwards or when the saved-state is restored; see Saving. Foreign resources are also unloaded when exiting Prolog execution. The parameter when reflects the context of the (un)load_foreign_resource/1 and is set as follows for init functions:

SP_WHEN_EXPLICIT
Explicit call to load_foreign_resource/1.
SP_WHEN_RESTORE
Resource is reloaded after save or restore.

For deinit functions:

SP_WHEN_EXPLICIT
Explicit call to unload_foreign_resource/1.
SP_WHEN_SAVE
Resource is unloaded before save.
SP_WHEN_EXIT
Resource is unloaded before exiting Prolog.