Problem exporting Haskell to C via a DLL in GHC 6.6

SevenThunders mattcbro at
Tue Feb 6 22:23:36 EST 2007

Brian Hulley wrote:
> Since Begin would be a function exported by the DLL, Windows would ensure 
> that the DLL was loaded when it is first called from your application if
> it 
> was not already loaded so there would be no need for an explicit call to 
> LoadLibrary.
>> and then End
>> specifically unload the library; or both?
> I wouldn't bother explicitly unloading the library - I'd leave this up to 
> Windows. The importance of using an End function is that you can ensure
> that 
> the call to shutdown Haskell happens at a time when all DLLs needed by 
> Haskell are still available, whereas using DllMain to do the shutdown call 
> is dangerous because DllMain may be invoked when some DLL necessary for 
> Haskell to shutdown has already been unloaded by Windows.
> Ideally there would also be some way to call Begin/End when using the DLL 
> from Matlab but I don't know anything about Matlab so can't help with
> this. 
> A quick hack to enable you to use the DLL safely from your application 
> (using Begin/End) as well as unsafely from Matlab (relying on DllMain to 
> shutdown Haskell), would just be to have a flag in the DLL to keep track
> of 
> whether you've already shut Haskell down. Then in the case for 
> process_detach you could just check this so that shutdown would only be 
> called from DllMain as a last resort.
>> Another question I have is, is it possible to create a statically
>> linked Haskell library that can be linked using MS VC tools?  Also I
>> must say I am a bit confused about the use of the routine
>> __stginit_Bad.  Suppose I had multiple Haskell modules each with
>> their own functions to export.  Which __stginit_??? routine do I use?
> I don't know - hopefully someone else may be able to answer this question.
> Best regards, Brian.
> -- 
> _______________________________________________
> Glasgow-haskell-users mailing list
> Glasgow-haskell-users at

In the final analysis this seems to work fairly well.  I export an End()
function to Matlab that calls
shutdownHaskell().  I then create a Matlab script that calls End() prior to
clearing the DLL out of the namespace.
Since it appears that shutdownHaskell() can be called again,  even after
it's already shut down without incident (at least from a few simple
experiments) it works fairly robustly.  All that needs to be done is to
remember to use the Matlab script as needed.

Meanwhile, it also appears I can call  the same routines from inside C,
letting windows do the DLL linkage, provided that shutdownHaskell() is NOT
called when the DLL unloads as you indicated earlier.  Thanks again for the
View this message in context:
Sent from the Haskell - Glasgow-haskell-users mailing list archive at

More information about the Glasgow-haskell-users mailing list