[Haskell-cafe] Troubles with FFI
Brian Hulley
brianh at metamilk.com
Sat May 13 10:51:27 EDT 2006
Matthew Bromberg wrote:
> foreign import ccall "matrix_c.h sumarr" sumarr :: Ptr CDouble ->
> CDouble [snip]
> If one changes the array in[] in the C code, e.g.
> double sumarr(double *in)
> {
> in[0] = -10.0 ;
> return(in[0] + in[1]) ;
> }
> The array is changed inside the haskell program as a side effect.
>
> main = do
> arr <- newListArray (1 , 3) [3,2,1]:: IO (StorableArray Int
> CDouble) -- extract the pointer to arr
> withStorableArray arr $ print . sumarr
> (readArray arr 1 ) >>= print
If you want to change the array in the C code, the foreign import should
reflect the fact that something is being mutated by enclosing the result in
the IO monad:
foreign import ccall "matrix_c.h sumarr" sumarr
:: Ptr CDouble ->IO CDouble
^^
(You don't need to change the type of the C function itself though)
Also, the 'a' in withStorableArray:: StorableArray i e -> (Ptr e -> IO a) ->
IO a is the result of your C function, which in this case is CDouble. It's
not related to the type of elements of the array.
So you could use:
withStorableArray arr $ sumarr >>= print
Operator precedences are given in
http://haskell.org/onlinereport/standard-prelude.html
I think FFI is one of these things that once you've understood it it seems
really neat and well thought out but it's as you say very difficult to get
into because you need to know everything all at once and the descriptions in
the FFI addendum are extremely terse and also very general, since they deal
with languages other than C as well.
Regards, Brian.
More information about the Haskell-Cafe
mailing list