Skip to content

Instantly share code, notes, and snippets.

@tmcdonell
Created June 14, 2019 17:35
Show Gist options
  • Save tmcdonell/ce6f2983c0fc77f9625db68e802fb3c4 to your computer and use it in GitHub Desktop.
Save tmcdonell/ce6f2983c0fc77f9625db68e802fb3c4 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdint.h>
#include <math.h>
double test1(double x)
{
return (x+1);
}
double test2(double x)
{
return sin(x);
}
{-# LANGUAGE OverloadedStrings #-}
import Text.Printf
import Foreign.Ptr
import Foreign.LibFFI -- package: libffi
import LLVM.Linking
import LLVM.OrcJIT
import LLVM.Internal.ObjectFile ( withObjectFile )
import qualified LLVM.Internal.OrcJIT.LinkingLayer as LL
resolveSymbol :: MangledSymbol -> IO (Either JITSymbolError JITSymbol)
resolveSymbol name = do
printf "looking for symbol: %s\n" (show name)
v <- getSymbolAddressInProcess name
if v == 0
then do
putStrLn "failed!"
return . Left $ JITSymbolError "is this error message ignored?"
else do
putStrLn "success!"
return . Right $ JITSymbol
{ jitSymbolAddress = v
, jitSymbolFlags = defaultJITSymbolFlags
}
main :: IO ()
main =
withExecutionSession $ \session ->
withModuleKey session $ \key ->
withSymbolResolver session (SymbolResolver resolveSymbol) $ \resolver ->
withObjectLinkingLayer session (\_ -> pure resolver) $ \linkingLayer ->
withObjectFile "./foo.o" $ \obj -> do
_ <- loadLibraryPermanently Nothing
addObjectFile linkingLayer key obj
-- NOTE: macOS requires the leading underscore to the function name; if
-- you are on another platform you should remove it
--
t1 <- LL.findSymbol linkingLayer "_test1" True
t2 <- LL.findSymbol linkingLayer "_test2" True
case t1 of
Left{} -> putStrLn "failed to load test1"
Right (JITSymbol f _) -> do
putStrLn "attempting to call test1"
r <- callFFI (castPtrToFunPtr (wordPtrToPtr f)) retCDouble [argCDouble 1]
printf "got result: %s\n" (show r)
case t2 of
Left{} -> putStrLn "failed to load test2"
Right (JITSymbol f _) -> do
putStrLn "attempting to call test2"
r <- callFFI (castPtrToFunPtr (wordPtrToPtr f)) retCDouble [argCDouble (pi/4)]
printf "got result: %s\n" (show r)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment