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);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With