New Extension: foreign C imports that return multiple values
I just implemented a new extension for jhc that I thought the community might have feedback on, it allows foreign imports of c routines to automaticall marshall multiple return values using the common fill in the pointer idiom used by the stardard C libraries. This completely removes most of the need for unsafePerformIO and the related Storable dependencies. Notably, many low lever floating point routines use this which really should be inlined and the optimizer can't see through the unsafePerformIO. here are the docs # foreign imports with multiple return values. foreign C imports may return multiple values. To indicate this is the case, use an unboxed tuple as the return value. The first return value will be the value the function directly returns, the rest will be passed as pointers at the end of the functions argument list. Only pure (non IO) functions may return multiple values. ~~~~ -- frexp has C prototype -- double frexp(double x, int *exp); -- so it would normally have an import like so, requiring the IO module and -- Storable to call what is otherwise a pure function. foreign import ccall "math.h frexp" c_frexp :: Double -> Ptr CInt -> IO Double -- This extension allows it to be declared as so foreign import ccall "math.h frexp" c_frexp :: Double -> (# Double, CInt #) -- The second return value is added as the last 'exp' parameter then read out -- of the allocated memory. The contents of the memory passed into the function -- is undefined. ~~~~ John
Interesting! -- Felipe.
On Fri, 10 Feb 2012, John Meacham wrote:
foreign import ccall "math.h frexp" c_frexp :: Double -> Ptr CInt -> IO Double
-- This extension allows it to be declared as so foreign import ccall "math.h frexp" c_frexp :: Double -> (# Double, CInt #)
-- The second return value is added as the last 'exp' parameter then read out -- of the allocated memory. The contents of the memory passed into the function -- is undefined.
Nice idea - how does JHC know where the pointer parameters are? Is it possible to have the pointer arguments at the first position?
participants (3)
-
Felipe Almeida Lessa -
Henning Thielemann -
John Meacham