[Haskell] Converting to Foreign types
Stefan O'Rear
stefanor at cox.net
Sat Feb 17 19:06:56 EST 2007
On Sat, Feb 17, 2007 at 05:58:49PM -0600, ROBERT DOUGLAS HOELZ wrote:
> Hello,
>
> I want to convert a Haskell Integer (Data.Int.Int32) to a C long (Foreign.C.Types.CLong), but it seems this code here doesn't work:
>
> intToLong :: Int32 -> Clong
> intToLong num =
> let maybelong = cast num
> in if isNothing maybelong
> then
> 0
> else
> fromJust maybeLong
>
> (It always returns 0)
>
> Could anyone give me a hint as to what the problem is?
cast has very limited abilities - it only converts if the types
are exactly the same, otherwise it returns Nothing.
In Haskell, Int32 and CLong are not the same type even if
they happen to be the same size; this helps with portability,
unlike C where code that assumes int32_t == long will work
flawlessly until it is run on a 64-bit computer.
You probably want to use Prelude.fromIntegral:
fromIntegral :: (Integral a, Num b) => a -> b
which converts between numeric types, with all the usual perils.
(e.g (fromIntegral :: Int -> Word8) 256 == 0)
Stefan
More information about the Haskell
mailing list