Next: , Previous: , Up: Calling C from Prolog   [Contents][Index]


6.2.6 Init and Deinit Functions

An init function and/or a deinit function can be declared by foreign_resource/2. If this is the case, then 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()), then 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, then 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 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 restore.

For deinit functions:

SP_WHEN_EXPLICIT

Explicit call to unload_foreign_resource/1 or a call to load_foreign_resource/1 with the name of an already loaded resource.

SP_WHEN_EXIT

Resource is unloaded before exiting Prolog.



Send feedback on this subject.