Ptr and ForeignPtr Questions

Ashley Yakeley ashley@semantic.org
Wed, 10 Oct 2001 01:19:05 -0700


At 2001-09-23 23:54, I wrote:

>As you point out, there are restrictions 
>on just what existing C functions you can bind to. If your function looks 
>like this:
>
>     const char* foo (struct SomeLinkedList*);
>
>...you have no choice but to write 'impedance-matching' code for that 
>function.

On second thought, I wonder if this is really true? It seems possible to 
declare a "raw" import and then use Haskell to adapt:

    foreign import "foo" raw_foo :: Ptr () -> IO (Ptr ());

    foo :: Ptr SomeLinkedList -> IO (ConstPtr Char);
    foo = importFunction raw_foo;

    instance Storable SomeLinkedList where
        {
        ...
        };

Of course you'd need a suitable definition of importFunction:

    class ConvertValueToRaw t r | t -> r where
        {
        importValue :: r -> t;
        exportValue :: t -> r;
        };

    class ConvertFunctionToRaw t r | t -> r where
        {
        importFunction :: r -> t;
        };

    instance (ConvertValueToRaw tv rv) =>
     ConvertFunctionToRaw (IO tv) (IO rv) where
        {
        importFunction rawF = do
            {
            rv <- rawF;
            return (importValue rv);
            };
        };

    instance (ConvertFunctionToRaw tb rb,ConvertValueToRaw ta ra) =>
     ConvertFunctionToRaw (ta -> tb) (ra -> rb) where
        {
        importFunction rawF ta = importFunction (rawF (exportValue ta));
        };

    instance ConvertValueToRaw (Ptr a) (Ptr ()) where
        {
        importValue = castPtr;
        exportValue = castPtr;
        };

    instance ConvertValueToRaw Word8 Word8 where
        {
        importValue = id;
        exportValue = id;
        };
    
    etc.



-- 
Ashley Yakeley, Seattle WA