You would need the NOINLINE pragma:

    {-# NOINLINE eventObj_ #-}
    eventObj_ :: Ptr Event
    eventObj_ = unsafePerformIO malloc

I would avoid this sort of global state in general.  It isn't clear that this will give an improvement in performance and what could otherwise possible be a thread safe API is no longer thread safe.  Global TVars and MVars are much more compelling as they are thread safe and represent some global synchronization in your program.


On Wed, Jan 29, 2014 at 10:03 AM, Ömer Sinan Ağacan <omeragacan@gmail.com> wrote:
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
http://osa1.net
_______________________________________________
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe