gpt4 book ai didi

C 语言的 Haskell 导出函数

转载 作者:行者123 更新时间:2023-12-02 12:05:49 25 4
gpt4 key购买 nike

我的代码:

getGPS :: String -> IO (Double, Double)
getGPS ip = do
html <- getHTML ip
let ztags =Prelude.zip [0..] . filterStr . getTagText . getTags $ html
let nlat = Prelude.head $ Prelude.map fst . Prelude.filter (\(_, str) -> strEq str ("Latitude:" :: String)) $ ztags
let nlng = Prelude.head $ Prelude.map fst . Prelude.filter (\(_, str) -> strEq str ("Longitude:" :: String)) $ ztags
let lat = read (Prelude.head $ Prelude.map snd . Prelude.filter (\(n, _) -> n == nlat + 1) $ ztags) :: Double
let lng = read (Prelude.head $ Prelude.map snd . Prelude.filter (\(n, _) -> n == nlng + 1) $ ztags) :: Double
return (lat, lng)

工作正常。现在我想通过 FFI 导出此函数以从 C 应用程序访问它。我做了 foreign export ccall getGPS::CString -> IO (CDouble, CDouble) 但这不起作用:

GPS.hs:45:1:
Illegal foreign declaration: requires unregisterised, llvm (-fllvm) or native code generation (-fasm)
When checking declaration:
foreign export ccall "getGPS" getGPS
:: CString -> IO (CDouble, CDouble)

GPS.hs:45:1:
Unacceptable result type in foreign declaration:
‘(CDouble, CDouble)’ cannot be marshalled in a foreign call
When checking declaration:
foreign export ccall "getGPS" getGPS
:: CString -> IO (CDouble, CDouble)

GPS.hs:45:1:
Couldn't match type ‘Double’ with ‘CDouble’
Expected type: CString -> IO (CDouble, CDouble)
Actual type: String -> IO (Double, Double)
In the expression: getGPS
When checking declaration:
foreign export ccall "getGPS" getGPS
:: CString -> IO (CDouble, CDouble)
Failed, modules loaded: none.

如何正确导出这个函数?

最佳答案

实际上有两个错误:

  • foreign export 的类型和 getGPS 函数必须匹配,因此您需要一个从 CString 到 CDouble 的 GPS 包装器(使用 peekCString > 和 CDouble 来转换它们)
  • 您不能使用元组作为返回参数。有多种解决方案,例如使用 2 个 Ptr CDouble 参数或定义一个结构。

所以一个可能的解决方案是

foreign export ccall "getGPS" getGPS' :: CString -> Ptr CDouble -> Ptr CDouble -> IO ()

getGPS' :: CString -> Ptr CDouble -> Ptr CDouble -> IO ()
getGPS' str d1 d2 = do
(r1, r2) <- getGPS =<< peekCString str
poke d1 (CDouble r1)
poke d2 (CDouble r2)

在 C 代码中使用时,请记住调用 hs_iniths_exit

关于C 语言的 Haskell 导出函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34189847/

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