Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing void * through haskell

Tags:

c

haskell

I'm working on a C library (libpandoc) that uses a haskell library (pandoc) to do some work. The C library gives the haskell wrapper callbacks to read and write data. Typical with callbacks, I would also like to send a void *user_data so that the callbacks would not have to depend on global variables.

Searching the internet however, I can't seem to figure out how to pass Haskell a void * variable.

There is the CString which is a char * (and can eventually be used as a workaround, but it's not so nice) and the general Ptr which makes pointers out of things. However, those things seem not to include void (which is also understandable). Looking at Foreign.C I don't see anything else that could be useful.

My question is, what type can I use to pass such a function to Haskell?

int func(char *buffer, void *user_data);

...

that_haskell_function(..., func, my_data);
like image 507
Shahbaz Avatar asked Jun 28 '13 14:06

Shahbaz


1 Answers

Any pointer type at all should work, I think, but Ptr () makes the most sense.

{-# LANGUAGE ForeignFunctionInterface #-}
import Foreign
import Numeric

foreign import ccall unsafe "foo"
    c_foo :: Ptr () -> IO ()

main :: IO ()
main =
    allocaBytes 8 $ \ptr -> do
        c_foo ptr
        x <- peek (castPtr ptr) :: IO Word64
        putStrLn (showHex x "")

And the C file:

#include <string.h>

void foo(void *ptr)
{
    memset(ptr, 0xEB, 8);
}

Gives the result:

ebebebebebebebeb
like image 117
Thomas M. DuBuisson Avatar answered Oct 10 '22 01:10

Thomas M. DuBuisson