Haskell inline-c-cpp call Haskell function

Viewed 271

I am using inline-c-cpp in a small example to reverse a String:

[C.block| void {
        static char strTest[128] = "Hello, Haskell!";
        c_func();
  } |]

The Haskell code are:

reverseIO :: BS.ByteString -> IO BS.ByteString
reverseIO str = return $ BS.reverse str

c_func() is defined in another c file that I included by C.include "test.c" In that test.c I call

$fun:(char * (*reverseIO)(char * ))(strTest)

I get several errors:

 error: use of undeclared identifier 'reverseIO'
              $fun:(char (*reverseIO)(char * ))(strTest)
                           ^

Could anyone help me get this right?

Update: I finally got it working with proper C function pointer syntax.

  [C.block| void {
           c_func($fun:(char* (*reverseIO)(char*)));
                         } |]

But still I have the type problem:

• Couldn't match type ‘BS.ByteString’ with ‘GHC.Ptr.Ptr CChar’
  Expected type: GHC.Ptr.Ptr CChar -> IO (GHC.Ptr.Ptr CChar)
    Actual type: BS.ByteString -> IO BS.ByteString
1 Answers

Finally got it working:

import           Data.Monoid           ((<>))
import           Foreign.C.String
import qualified Language.C.Inline.Cpp as C

C.context (C.cppCtx <> C.baseCtx  <>C.funCtx)

C.include "pageturnerui.cpp"

someFunc :: IO ()
someFunc = do
  let reverseIO :: CString -> IO CString
      reverseIO cs = peekCString cs >>= return. reverse >>= newCString

  [C.block| void {
      pageturnerui($fun:(char* (*reverseIO)(char *)));
                         } |]

In my pageturnerui.cpp:

int pageturnerui(char* (*foo)(char*))
{
...
            static char strTest[128] = "Hello, Haskell!";

            if (ImGui::Button("Button")) {
              strcpy(strTest, foo(strTest));
            }
...
}

PS: My code doesn't illustrate the best practice. I'm not experienced enough to be able to provide advice on that. Just showing that it compiles and works and didn't crash.

Related