Why does sizeOf Word64 = 4?

Alastair Reid alastair at reid-consulting-uk.ltd.uk
Sun Nov 9 08:51:11 EST 2003


> Hi, I'm trying to learn about Haskell's FFI (running 6.0.1 on linux)
> and see the following weird behavior with ghci:

You're seeing the right behaviour.

> Shouldn't "sizeOf nullPtr" return an error?  And sizeOf a Ptr Word64
> should be 8 I think.

The size of a Word64 value is 8 but the size of a pointer is always the same 
no matter what the pointer points to.  Since most machines have 32-bit 
addresses, the size of a pointer will be 4 on most machines.

A null pointer is just another machine address and has to be the same size as 
any other machine address so, again, it has to be the same size.

> Also this program prints "4", when it seems it
> should print "8":
>
> 	module Main where
> 	import Data.Word
> 	import Foreign.Storable
> 	import Foreign.Ptr
> 	import Foreign.StablePtr
>
> 	x :: Word64
> 	x = 5
>
> 	main = do x_sptr <- newStablePtr 5
> 	          putStrLn $ show $ sizeOf x_sptr

This is a stable pointer to an Int.
Again, the type and, in particular, the size of the thing pointed
 to is irrelevant.
I can't be bothered looking it up but the size returned is either
 the size of a machine address (void* in C) or the size of int in C.
 Either way it is 4 on most machines.

It looks like you intended to create a stable pointer to x which is
 a Word64.  This would not have affected the result.  Indeed, you
 could have created a stable pointer to a complex Haskell data structure
 like a binary tree or a function (i.e., something the FFI doesn't
 directly support) and the size would still be the same because all you
 are doing is passing a pointer to the object.

--
Alastair Reid    www.haskell-consulting.com





More information about the Glasgow-haskell-users mailing list