在一个小示例中,我使用inline-c-cpp来反转字符串:
[C.block| void {
static char strTest[128] = "Hello, Haskell!";
c_func();
} |]
Haskell代码为:
reverseIO :: BS.ByteString -> IO BS.ByteString
reverseIO str = return $ BS.reverse str
c_func()
在另一个C.include "test.c"
中包含的c文件中定义
在那个test.c
中,我打电话
$fun:(char * (*reverseIO)(char * ))(strTest)
我遇到几个错误:
error: use of undeclared identifier 'reverseIO'
$fun:(char (*reverseIO)(char * ))(strTest)
^
有人可以帮我弄对吗?
更新: 我终于可以使用正确的C函数指针语法来工作了。
[C.block| void {
c_func($fun:(char* (*reverseIO)(char*)));
} |]
但是我仍然遇到类型问题:
• 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
答案 0 :(得分:2)
最终使其正常工作:
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 *)));
} |]
在我的pageturnerui.cpp中:
int pageturnerui(char* (*foo)(char*))
{
...
static char strTest[128] = "Hello, Haskell!";
if (ImGui::Button("Button")) {
strcpy(strTest, foo(strTest));
}
...
}
PS:我的代码未说明最佳实践。我经验不足,无法就此提供建议。只是表明它可以编译,运行并且没有崩溃。