
shackell:
On Sun, 2006-09-17 at 18:31 +0200, C??dric Paternotte wrote:
Hi,
I was wondering whether Yhc was able to provide dynamic loading of modules.
Let's say I'd wanted to do something like :
myFiboFunction <- loadModule "myPlugin.hbc" "myFiboFunction" putStrlLn $ myFiboFunction 10
Is it possible to achieve this in the current state of Yhc ? I know there's an API out there to load bytecodes at runtime but I'm not sure it's meant to do that...
Hi Cedric,
There is indeed a RuntimeAPI, though it's still in the process of being written so it's a bit low level. At somepoint we'll write a user-friendly library over the top but at present your example would be:
import YHC.Runtime.API
main = do let typ = undefined :: Int -> Int fibo <- loadFromModule "MyPlugin" "myFiboFunction" typ putStrLn $ show $ fibo 10
loadFromModule :: String -> String -> a -> IO a loadFromModule mod obj typ = do pluginModule <- moduleLoad mod case pluginModule of Nothing -> error $ "couldn't load module '"++mod++"'" Just m -> do fiboNode <- moduleLookupNode m obj case fiboNode of Nothing -> error $ "could not find '"++obj++ "' in module '"++mod++"'" Just n -> do typRep <- getType typ withNode n typRep $ \ fibo -> return fibo
Notice that it's necessary to give a dummy parameter of the correct type to keep the type system happy. Also be wary that the system currently doesn't check that the type is correct so doing:
... let typ = undefined :: Float -> Char ..
Will compile and even execute, but will prompty crash horribly. In future we'll add type checking so it'll give a sensible runtime error.
Hope that helps :-)
Hmm, from here it wouldn't be too hard I think to add eval :: String -> IO a would it? eval s = do writeFile "tmp.hs" s yhc "-c" "tmp.hs" -- run the compiler, get a .o bytecode file (?) loadFromModule "tmp.o" .. or even a nicer interface might exist? Tom? /me has visions of fast bytecode eval for lambdabot. -- Don