Advanced Topics

Memory management issues

BlitzMax currently uses an optimized form of reference counting to implement memory management. This technique is fast and deterministic: you control exactly when memory is reclaimed by the system making it ideal for realtime applications like games.

However, there is one situation where you need to be a bit careful about memory management and that is when you are dealing with cyclic data structures.

A cyclic data structure is a data structure (in BlitzMax, a user defined type) that can potentially 'point to itself'. The most extreme example of a cyclic data structure is something like:
Type TCyclic
	Field cycle:TCyclic=Self
End Type

For k=1 To 10
	Local cyclic:TCyclic=New TCyclic
	FlushMem
	Print MemAlloced()
Next
If you run this program, you will notice that memory is slowly leaking. This is happening because the reference count for each TCyclic object never reaches 0, thanks to the objects 'cyclic' field.

It is therefore necessary to ensure such cyclic data structures are cleanly handled. This can be achieved by adding a method to 'unlink' any such cycles. For example:
Type TCyclic
	Field cycle:TCyclic=Self
	
	Method Remove()
		cycle=Null
	End Method
	
End Type

For k=1 To 10
	Local cyclic:TCyclic=New TCyclic
	FlushMem
	Print MemAlloced()
	cyclic.Remove
Next
In real world use this problem seldom arises, and when it does it's typically when designing container types. Indeed, in this author's opinion, a cyclic data structure is often a sign of poor design - object dependancies should ideally form a cycle-free tree.

If you are at all worried about this, you can easily track memory usage with the MemAlloced() function from the BlitzMax runtime library which provides a very accurate measure of memory usage.

Interfacing with other languages

You can use the Import command to add certain non-BlitzMax source files to your projects, and the Extern command to make the functions in those files visible to BlitzMax applications.

The currently supported non-BlitzMax source file types are: .c (C), .cpp (C++), .m (ObjectiveC) and .s (Assembler).

BlitzMax will use the GNU compiler tools to compile C, C++ and ObjectiveC files, and either the 'fasm' assembler for x86 assembly or GNU assembler for PowerPC assembly.

Here is a simple example of importing 'C' source code into your project and accessing a 'C' function:
//----- file: c_funcs.c -----
int Doubler( int x ){
	return x+x;
}

'----- file: app.bmx -----
Import "c_funcs.c"

Extern
	Function Doubler( x )
End Extern

Print Doubler(10)