我自己使用 GHC 成功地复制了这个例子。
https://wiki.haskell.org/Calling_Haskell_from_C
最终目标是用 Haskell 编写 99% 的程序,然后从用 C 编写的事件循环中调用它:
#include <HsFFI.h>
#ifdef __GLASGOW_HASKELL__
#include "../.stack-work/dist/x86_64-linux/Cabal-2.4.0.1/build/Lib_stub.h"
extern void __stginit_Lib(void);
#endif
#include <stdio.h>
#include <time.h>
extern void hs_add_root (void (*init_root)(void));
int main(int argc, char *argv[])
{
int i;
hs_init(&argc, &argv);
#ifdef __GLASGOW_HASKELL__
hs_add_root(__stginit_Lib);
#endif
for (int m = 0; m < 10; ++m) {
i = fibonacci_hs(42);
printf("Fibonacci: %d\n", i);
}
hs_exit();
return 0;
}
在 C 中运行事件循环的动机是,据我所知,在 Haskell 中强制评估 X 次/秒是困难的或不可能的。
这是 package.yaml:
name: c-loop
version: 0.1.0.0
github: "githubuser/c-loop"
license: BSD3
author: "Author name here"
maintainer: "example@example.com"
copyright: "2019 Author name here"
extra-source-files:
- README.md
- ChangeLog.md
# Metadata used when publishing your package
# synopsis: Short description of your package
# category: Web
# To avoid duplicated efforts in documentation and dealing with the
# complications of embedding Haddock markup inside cabal files, it is
# common to point users to the README.md file.
description: Please see the README on GitHub at <https://github.com/githubuser/c-loop#readme>
dependencies:
- base >= 4.7 && < 5
library:
source-dirs: src
executables:
c-loop-exe:
main: Main.hs
source-dirs: app
ghc-options:
- -threaded
- -rtsopts
- -with-rtsopts=-N
- -fobject-code
# - -no-hs-main
- --make -no-hs-main -optc-O ./c/eventLoop.c Lib -o eventLoop
dependencies:
- c-loop
tests:
c-loop-test:
main: Spec.hs
source-dirs: test
ghc-options:
- -threaded
- -rtsopts
- -with-rtsopts=-N
dependencies:
- c-loop
当我运行时:
$ stack build
我明白了:
<no location info>: error: module ‘Lib’ cannot be found locally
有谁知道发生了什么?