gpt4 book ai didi

haskell - 动态加载已编译的 Haskell 模块 - GHC 7.6

转载 作者:行者123 更新时间:2023-12-04 00:56:34 27 4
gpt4 key购买 nike

我正在尝试使用 GHC API 动态编译和加载 Haskell 模块。我知道 API 从一个版本到另一个版本波动很大,所以我专门谈论 GHC 7.6.*。

我尝试在 MacOS 和 Linux 上运行相同的代码。在这两种情况下,插件模块都可以正常编译,但在加载时会出现以下错误:Cannot add module Plugin to context: not interpreted
问题类似于this 中的问题。只有在主机程序的同一运行中编译模块时才会加载该模块。

-- Host.hs: compile with ghc-7.6.*
-- $ ghc -package ghc -package ghc-paths Host.hs
-- Needs Plugin.hs in the same directory.
module Main where

import GHC
import GHC.Paths ( libdir )
import DynFlags
import Unsafe.Coerce

main :: IO ()
main =
defaultErrorHandler defaultFatalMessager defaultFlushOut $ do
result <- runGhc (Just libdir) $ do
dflags <- getSessionDynFlags
setSessionDynFlags dflags
target <- guessTarget "Plugin.hs" Nothing
setTargets [target]
r <- load LoadAllTargets
case r of
Failed -> error "Compilation failed"
Succeeded -> do
setContext [IIModule (mkModuleName "Plugin")]
result <- compileExpr ("Plugin.getInt")
let result' = unsafeCoerce result :: Int
return result'
print result

和插件:
-- Plugin.hs
module Plugin where

getInt :: Int
getInt = 33

最佳答案

问题是您正在使用 IIModule .这表明您希望将模块及其中的所有内容(包括未导出的内容)带入上下文。与 :load 基本相同在 GHCi 中带有星号。正如您所注意到的,这仅适用于解释代码,因为它让您“查看”模块。

但这不是你在这里需要的。你想要的是像使用 :module 一样加载它。或 import声明,它适用于已编译的模块。为此,您使用 IIDecl它需要一个进口声明,您可以使用 simpleImportDecl :

setContext [IIDecl $ simpleImportDecl (mkModuleName "Plugin")]

关于haskell - 动态加载已编译的 Haskell 模块 - GHC 7.6,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16806460/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com