Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ================ CInterface.hsc =====================
- {-# LANGUAGE ForeignFunctionInterface #-}
- module CInterface where
- import Foreign.C
- import Foreign.Storable
- import Foreign.Ptr
- import Data.Bits
- foreign export ccall printInput :: Ptr Input -> IO ()
- data Input = Input { alpha :: Bool
- , beta :: Bool } deriving (Eq, Show)
- -- from http://www.haskell.org/haskellwiki/FFI_cook_book
- #let alignment t = "%lu", (unsigned long)offsetof(struct {char x__; t (y__); }, y__)
- #def typedef struct {
- union {
- struct {
- unsigned char alpha : 1;
- unsigned char beta : 1;
- unsigned char reserved : 6;
- } baz;
- unsigned char baz_all;
- };
- } input_t;
- instance Storable Input where
- alignment _ = #{alignment input_t}
- sizeOf _ = #{size input_t}
- peek ptr = do
- b <- ( #{peek input_t, baz_all} ptr )::IO CUChar
- return Input { alpha = testBit b 0
- , beta = testBit b 1 }
- poke ptr inp = undefined
- printInput :: Ptr Input -> IO ()
- printInput pInp = do
- inp <- peek pInp
- putStrLn $ show inp
- ================ ctest.c =====================
- #include "HsFFI.h"
- #include "CInterface_stub.h"
- #include "CInterface_hsc.h"
- #include "dll_init.h"
- int main(int argc, char* argv[]) {
- sp_init(&argc,&argv);
- ////////////////////////////////////////
- input_t inp = {0};
- inp.baz.alpha = 1;
- inp.baz.beta = 0;
- printInput( &inp );
- ////////////////////////////////////////
- sp_exit();
- return 0;
- }
- ================ dll_init.h =====================
- #pragma once
- extern void __stginit_CInterface(void);
- extern void sp_init(int*, char***);
- extern void sp_exit(void);
- ================ dll_init.c =====================
- #include "HsFFI.h"
- #include "dll_init.h"
- void sp_init(int* p_argc, char*** p_argv) {
- hs_init(p_argc, p_argv);
- hs_add_root(__stginit_CInterface);
- }
- void sp_exit(void) {
- hs_exit();
- }
- =================== test.cabal =====================
- name: test
- version: 0.0
- cabal-version: >1.2
- synopsis: <Project description>
- description: <Project description>
- category: Codec
- license: BSD3
- license-file: LICENSE
- author: # example, `Fred Bloggs
- maintainer: fred@example.net
- build-depends: base >=4 && <5
- build-type: Simple
- library
- build-depends: base >=4 && <5
- exposed-modules: CInterface
- c-sources: dll_init.c
- ghc-options: -threaded
- ====================== LICENSE ===============
- ====================== Setup.lhs ==============
- #!/usr/bin/env runhaskell
- > import Distribution.Simple
- > main = defaultMain
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement