how to bind a c function which populates a pointer in haskell

Viewed 26

So I'm lurking around Haskell ffi trying to figure how to do stuff. I've bound couple functions which take and return integer values. Now I want to bind a function which takes a pointer to a buffer, which it populates. But Haskell doesn't have variables - it seems I can define a constant of type CIntPtr which i can then cast to CCharPtr and use sizeOf to get the buffer size, but how would i access the value later in said buffer afterwards?

I'm struggling to find a minimal example of binding a function which takes a pointer where it writes some value and accessing that value from haskell code.

Could anyone help me by providing / pointing one? In case a more specific question is required: lets assume I want to bindpipe syscall, call it, and get the values from haskell code.

1 Answers

You can use functions from the Foreign.Marshal.Array module. Here's an example:

hello.c

void do_something(int* values) {
    values[0] = 1;
    values[1] = 2;
    values[2] = 3;
}

Lib.hs

import Foreign.C
import Foreign.Ptr
import Foreign.Marshal.Array

foreign import ccall "do_something"
    c_do_something :: Ptr CInt -> IO ()

someFunc :: IO ()
someFunc = do
    xs <- allocaArray 10 $ \ptr -> do
        c_do_something ptr
        peekArray 10 ptr
    print xs

Executing this prints the following:

[1,2,3,0,0,0,0,0,0,0]
Related