[Haskell-cafe] Is it safe to create global variables using unsafePerformIO?

Ömer Sinan Ağacan omeragacan at gmail.com
Wed Jan 29 15:03:23 UTC 2014

I was also wondering a similar thing. I'm writing FFI for a C library.
Library has a function like:

    int pollEvent(EventType* event);

Instead of malloc'ing a new EventType in a FFI call for this functions:

    pollEvent :: IO Event
    pollEvent = do
      ev <- malloc
      ret <- cPollEvent ev
      -- check if ret is 0 etc.
      peek ev

I was wondering if something like this is also safe:

    eventObj_ :: Ptr Event
    eventObj_ = unsafePerformIO malloc

    pollEvent :: IO Event
    pollEvent = do
      ret <- cPollEvent eventObj_
      -- check if ret is 0 etc.
      peek eventObj_

This is one malloc cheaper for every call, and differences are not
visible from user side. Still, I did not use this in my FFI bindings
because I was not sure how safe is this approach. Any ideas on this?

Ömer Sinan Ağacan

More information about the Haskell-Cafe mailing list