如何通过从哈斯克尔到C字符串? [英] How to pass a string from Haskell to C?

查看:124
本文介绍了如何通过从哈斯克尔到C字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所有我想要做的就是从哈斯克尔传递一个纯文本字符串到C.然而,它说,[字符]是不可接受的返回类型。我找不到任何地方,为什么他们认为这是,类型也不是什么可以接受的回报。

我试图让我可以使用QEMU进行引导一个非常简单的操作系统镜像。

有谁知道如何做到这一点?谢谢你。

  { - #语言ForeignFunctionInterface# - }    模块你好在哪里    国外进口
    进口Foreign.C.String
    进口Foreign.C.Types    你好::字符串 - > (CString的 - > IO一) - GT;一个IO
    你好=你好,世界!    外贸出口ccall你好::字符串 - > (CString的 - > IO一) - GT;一个IO


解决方案

您希望有一个的CString

的CString 字符串

  peekCString :: CString的 - > IO字符串

字符串的CString

  withCString ::字符串 - > (CString的 - > IO一) -  GT;一个IO

还有 Foreign.C.String 。

这可以在海外声明中使用的类型总表被指定为的 /haskell2010/haskellch8.html#x15-1490008\">Foreign功能接口。

修改

好吧,这里的事情可以做,有些根据样品code一个非常小的例子。创建一个Haskell文件 CTest.hs 包含以下内容:

 模块CTEST哪里进口Foreign.C你好:: IO CString的
你好= newCString你好外贸出口ccall你好:: IO CString的

然后创建一个C文件 ctest.c 包含以下内容:

 的#include<&stdio.h中GT;
#包括CTest_stub.hINT主(INT ARGC,CHAR *的argv []){
  hs_init(安培; ARGC,&安培; argv的);
  的printf(%S \\ n,你好());
  hs_exit();
  返回0;
}

然后编译并运行如下:

  $ GHC CTEST
[1 1]编译CTEST(CTest.hs,CTest.o)
$ GHC -o CTEST ctest.c CTest.o -no-HS-主
$ ./ctest
你好

All I want to do is pass a plain-text string from Haskell to C. However, it says that [Char] is an unacceptable return type. I can't find anywhere why they think it is, nor what acceptable return types are.

I'm trying to make a very simple OS image that I can boot with Qemu.

Does anyone know how to do this? Thanks.

    {-# LANGUAGE ForeignFunctionInterface #-}

    module Hello where

    import Foreign
    import Foreign.C.String
    import Foreign.C.Types

    hello :: String -> (CString -> IO a) -> IO a
    hello = "Hello, world!"

    foreign export ccall hello :: String -> (CString -> IO a) -> IO a

解决方案

You want a CString.

Going from CString to String:

peekCString :: CString -> IO String

Going from String to CString:

withCString :: String -> (CString -> IO a) -> IO a

There's also Haddock documentation for module Foreign.C.String.

The general list of types that can be used in foreign declarations is specified as part of the Foreign Function Interface in the Haskell Report.

Edit

Ok, here's a very small example of a thing you can do, somewhat based on your sample code. Create a Haskell file CTest.hs with the following contents:

module CTest where

import Foreign.C

hello :: IO CString
hello = newCString "hello"

foreign export ccall hello :: IO CString

Then create a C file ctest.c with the following contents:

#include <stdio.h>
#include "CTest_stub.h"

int main (int argc, char *argv[]) {
  hs_init(&argc, &argv);
  printf("%s\n", hello());
  hs_exit();
  return 0;
}

Then compile and run as follows:

$ ghc CTest
[1 of 1] Compiling CTest            ( CTest.hs, CTest.o )
$ ghc -o ctest ctest.c CTest.o -no-hs-main
$ ./ctest
hello

这篇关于如何通过从哈斯克尔到C字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆