c - 堆栈如何使用外部函数接口(interface) (FFI)?

标签 c haskell ffi haskell-stack

我正在关注一些 FFI 教程和示例( herehere ),我想知道使用堆栈时应该改变什么?

在示例中,源 C 文件使用 gcc -c -o termops.o termops.c 编译为目标文件。并使用 ghc --make -main-is FfiEx -o ffi_ex FfiEx.hs termops.o 包含在 gcc 编译中.使用堆栈如何实现等效?

最佳答案

这是我能想象到的最小的 FFI C 项目。

$ cd c-proj
c-proj$ ls
Main.hs      c-proj.cabal c_file.c

这些文件的内容:
  • c-proj.cabal : 描述
    name:            c-proj
    version:         0.1.0.0
    cabal-version:   >= 1.22
    build-type:      Simple
    
    executable main
      main-is:       Main.hs
      build-depends: base >= 4.9
      c-sources:     c_file.c
    
  • Main.hs :唯一的 Haskell 源文件
    {-# LANGUAGE ForeignFunctionInterface #-}
    
    module Main where
    
    foreign import ccall "plus_ten" plusTen :: Int -> IO Int
    
    main = do
      n <- plusTen 2
      print n
    
  • c_file.c : C 源文件
    #include<stdio.h>
    
    int plus_ten(int n) {
      printf("%d + 10\n", n);
      return n + 10;
    }
    

  • 然后,如果你想使用 Stack,你可以运行 stack init .
    $ stack init
    << Shell output snipped >>
    $ stack build
    << Shell output snipped >>
    $ stack exec main
    2 + 10
    12
    

    关于c - 堆栈如何使用外部函数接口(interface) (FFI)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46576861/

    相关文章:

    Haskell 无限循环,只需简单的 re-let 操作

    haskell - 为什么这个美元符号结构不起作用?

    haskell - 将混合可存储向量传递给 C 函数

    c++ - 从 'cmath' 和 'cstdlib' 得到一百个非常相似的编译器错误

    Haskell 风格和类型类设计(类型类应该最小化吗?)

    c - 在c中如何从该字符串中获取第一个字符?

    c++ - 当通过 FFI 从 Rust 调用时,您如何使用返回 shared_ptr<T> 的 C++ 函数?

    lisp - 如何使用不对称(未配对)的任意括号创建宏

    c - 调试断言失败,表达式 : (unsigned)(c + 1) <=256

    c - 找到C程序的输出