Search code examples
pointershaskellffiampersand

Haskell's Foreign.C equivalent of C's ampersand operator (&)


As you will know, for any identifier ident in C, you can write &ident to obtain the memory location (pointer) to ident, regardless of whether that location is on the heap or on the stack. Whilst working with C types, it is often helpful to have access to this functionality.

Is there an equivalent operation in Haskell in the FFI?


Solution

  • If you have a C identifier you're importing into Haskell, you can convert it to a pointer to that address via the "&" syntax in FFI declarations, like so:

    foreign import ccall "&" bar :: Ptr CInt
    

    Typically this is quite a rare thing to do, as almost everything you import is already a pointer.

    Haskell values themselves may also be turned into pointers, using stable pointers, to ensure they're unaffected by the garbage collector.