Haskell FFI how to take an address of the local value -
i try work simple c-code haskell:
time_t rawtime = time( null ); struct tm* timeinfo = localtime( &rawtime ); /* using address of local variable */ printf( "the current date is: %s", asctime( timeinfo ) );
so write:
data ctmstruct = ctmstruct type ctmstructptr = ptr ctmstruct foreign import ccall "time" c_time :: ptr ctime -> io ctime foreign import ccall "localtime" c_localtime :: ptr ctime -> io ctmstructptr foreign import ccall "asctime" c_asctime :: ctmstructptr -> cstring main :: io () main = rawtime <- c_time nullptr tmstructptr <- c_localtime ??? -- how address of rawtime? print $ c_asctime tmstructptr
so how can address of local value rawtime
putting argument of c_localtime
function? i've read documentation foreign
module, didn't find answer question. i'd grateful help.
i able do:
import foreign.c.string import foreign.marshal.alloc -- declarations , foreign bindings here gettime :: io string gettime = p <- malloc c_time p tmptr <- c_localtime p str <- peekcstring $ c_asctime tmptr free p return str main :: io () main = currenttime <- gettime putstrln currenttime
the key using malloc
, free
, explicitly allocate space, pass c_time
set contents, c_localtime
format ctmstruct
, pass c_asctime
convert cstring
, marshal haskell string
peekcstring
, , free pointer used time.
i guess should have realized sooner, better solution use alloca
:
gettime :: io string gettime = alloca $ \p -> c_time p tm <- c_localtime p peekcstring $ c_astime tm
which safer, shorter, , easier. alloca
function allocation , freeing of pointer you, have use it.
Comments
Post a Comment