gpt4 book ai didi

memory - 如何在 Haskell 中获取指针值?

转载 作者:IT王子 更新时间:2023-10-28 23:32:42 25 4
gpt4 key购买 nike

我希望在非常低的级别上操作数据。

因此,我有一个函数,它接收一个整数形式的虚拟内存地址,并用这个内存地址“做事”。我从 C 中接口(interface)了这个函数,所以它的类型是 (CUInt -> a)。我要链接的内存是文件中的 Word8 。遗憾的是,我不知道如何访问该 Word8 的指针值。

要清楚,我不需要Word8的值,我需要虚拟内存地址的值,也就是指向它的指针的值。

最佳答案

为了一个简单的例子,假设你想给指针添加一个偏移量。

前题:

module Main where
import Control.Monad (forM_)
import Data.Char (chr)
import Data.Word (Word8)
import Foreign.ForeignPtr (ForeignPtr, withForeignPtr)
import Foreign.Ptr (Ptr, plusPtr)
import Foreign.Storable (peek)
import System.IO.MMap (Mode(ReadOnly), mmapFileForeignPtr)

是的,您写道您不想要 Word8 的值,但我已使用 peek 检索它以证明该指针是有效的。您可能想从withForeignPtr 内部return Ptr ,但文档警告不要这样做:

Note that it is not safe to return the pointer from the action and use it after the action completes. All uses of the pointer should be inside the withForeignPtr bracket. The reason for this unsafeness is the same as for unsafeForeignPtrToPtr below: the finalizer may run earlier than expected, because the compiler can only track usage of the ForeignPtr object, not a Ptr object made from it.

代码很简单:

doStuff :: ForeignPtr Word8 -> Int -> IO ()
doStuff fp i =
withForeignPtr fp $ \p -> do
let addr = p `plusPtr` i
val <- peek addr :: IO Word8
print (addr, val, chr $ fromIntegral val)

为了从您的问题中近似“文件中的 Word8”,主程序内存映射一个文件并使用该缓冲区来处理内存地址。

main :: IO ()
main = do
(p,offset,size) <- mmapFileForeignPtr path mode range
forM_ [0 .. size-1] $ \i -> do
doStuff p (offset + i)
where
path = "/tmp/input.dat"
mode = ReadOnly
range = Nothing
-- range = Just (4,3)

输出:

(0x00007f1b40edd000,71,'G')(0x00007f1b40edd001,117,'u')(0x00007f1b40edd002,116,'t')(0x00007f1b40edd003,101,'e')(0x00007f1b40edd004,110,'n')(0x00007f1b40edd005,32,' ')(0x00007f1b40edd006,77,'M')(0x00007f1b40edd007,111,'o')(0x00007f1b40edd008,114,'r')(0x00007f1b40edd009,103,'g')(0x00007f1b40edd00a,101,'e')(0x00007f1b40edd00b,110,'n')(0x00007f1b40edd00c,33,'!')(0x00007f1b40edd00d,10,'\n')

关于memory - 如何在 Haskell 中获取指针值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2386210/

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