Haskell:将DWORD值导入Windows注册表

时间:2013-11-10 18:18:46

标签: windows winapi haskell registry

我想编写一个小程序,从文本文件中读取数据,然后将其导入Windows注册表。我在System.Win32.Registry包中找到了对Windows函数的绑定,但遇到了regSetValueEx函数的问题。当我想将一个数字导入为DWORD(Word32)时,我无法弄清楚如何将它传递给regSetValueEx以获得所需的结果。

现在我将数字存储为TCHAR并使用alloca和poke来获取指针。这是我用于测试的代码:

module Main where

import           Foreign.Marshal.Alloc
import           Foreign.Storable
import           System.Win32.Registry
import           System.Win32.Types

number :: TCHAR
number = 42

getKey :: IO HKEY
getKey = regOpenKey hKEY_CURRENT_USER "test"

importFromTCHAR :: IO ()
importFromTCHAR = alloca $ \ptr -> do
                  poke ptr number
                  key <- getKey
                  regSetValueEx key "tchar" rEG_DWORD ptr (sizeOf (undefined::DWORD))

main :: IO ()
main = importFromTCHAR

结果:0x0184002a

它有点工作,但由于TCHAR值的大小只有2个字节,其他两个字节被垃圾占用。我怎么能阻止这个?任何帮助将不胜感激。我对Haskell很新(最近刚刚完成了LYAH),所以请放轻松我。 :)

另外,我真的很想知道Haskellers使用哪些库来与Windows注册表进行交互。是否有任何库可以更容易地使用它?

编辑:好的,因为在查看Hackage上的软件包时,我不知道错过了Foreign.Ptr包中的castPtr函数。我觉得自己像个白痴,因为有了这个解决方案真的很容易。根据Ilya的回答,我只需将数字存储为Word32(或DWORD),将其戳入指针alloca给我,然后在将其传递给regSetValueEx之前调用castPtr。这是修改后的代码:

module Main where

import           Foreign.Marshal.Alloc
import           Foreign.Ptr
import           Foreign.Storable
import           System.Win32.Registry
import           System.Win32.Types

number :: DWORD
number = 42

getKey :: IO HKEY
getKey = regOpenKey hKEY_CURRENT_USER "test"

importFromDWORD :: IO ()
importFromDWORD = alloca $ \ptr -> do
                  poke ptr number
                  key <- getKey
                  regSetValueEx key "dword" rEG_DWORD (castPtr ptr) (sizeOf number)

main :: IO ()
main = importFromDWORD

1 个答案:

答案 0 :(得分:1)

只需从Data.Word中将数字定义为Word32:

number :: Word32
number = 42

您也可以在正常值上使用sizeOf,例如:sizeOf number