DLLs, callbacks, and the GC that loves them

BlitzMax Forums/BlitzMax Programming/DLLs, callbacks, and the GC that loves them

This is definitely a very useful thread. Just for the sake of making a few things more complete, the line:

Function MyFunction( callback:Int() ) "win32"


should be:

Function MyFunction( callback:Int() "win32" ) "win32"


to prevent any crashes when the code is called from the C/C++ side.

Here is an example of this in action:

BMX code
Function edxGetGraphicsModes(callback(width:Int, height:Int, depth:Int, hertz:Int) "Win32") "Win32"
	GCEnter() ;
	For Local mode:TGraphicsMode = EachIn GraphicsModes()
		GCLeave() ;
		callback(mode.width, mode.height, mode.depth, mode.hertz) ;
		GCEnter() ;
	Next
End Function


C/C++ Code
// This declares a function pointer object, 
// I use ASM to assign it so I do not have to do 2x work writing out the function type and casting GetProcAddress
void	(__stdcall *GetGraphicsModes)		(void (__stdcall*)(int width, int height, int depth, int hertz));

...

// Load the function address from the DLL //

...

// Our callback function that handles the data
void __stdcall OnGraphicsMode(int width, int height, int depth, int hertz)
{
	printf("%i x %i x %i %ihz\n", width, height, depth, hertz);
}

...

// In some function
GetGraphicsModes(OnGraphicsMode);

...



Now, the OnGraphicsMode callback function will be properly invoked each call generated from the GraphicsModes iteration and not crash.

Thanks for the information Leadwerks!