Next: , Previous: Using pragma foreign_code for C, Up: Interfacing with C   [Contents] Memory management for C

Passing pointers to dynamically-allocated memory from Mercury to code written in other languages, or vice versa, is in general implementation-dependent.

The current Mercury implementation supports two different methods of memory management: conservative garbage collection, or no garbage collection. (With the latter method, heap storage is reclaimed only on backtracking.)

Conservative garbage collection makes inter-language calls simplest. When using conservative garbage collection, heap storage is reclaimed automatically. Pointers to dynamically-allocated memory can be passed to and from C without taking any special precautions.

When using no garbage collection, you must be careful not to retain pointers to memory on the Mercury heap after Mercury has backtracked to before the point where that memory was allocated. You must also avoid the use of the macros MR_list_empty() and MR_list_cons(). (The reason for this is that they may access Mercury’s ‘MR_hp’ register, which might not be valid in C code. Using them in the bodies of procedures defined using ‘pragma foreign_proc’ with ‘will_not_call_mercury’ would probably work, but we don’t advise it.) Instead, you can write Mercury functions to perform these actions and use ‘pragma foreign_export’ to access them from C. This alternative method also works with conservative garbage collection.

Future Mercury implementations may use non-conservative methods of garbage collection. For such implementations, it will be necessary to explicitly register pointers passed to C with the garbage collector. The mechanism for doing this has not yet been decided on. It would be desirable to provide a single memory management interface for use when interfacing with other languages that can work for all methods of memory management, but more implementation experience is needed before we can formulate such an interface.

Next: , Previous: Using pragma foreign_code for C, Up: Interfacing with C   [Contents]