Use another language to call a function: Difference between revisions

added Haskell example
(→‎{{header|D}}: removed D, doesn't fit the task description)
(added Haskell example)
Line 156:
Here am I
</pre>
 
=={{header|Haskell}}==
I modified the C source to include Haskell-specific headers and to init the Haskell environment. I also changed "Query" to "query_hs" due to capitalization issues:
<lang c>
#ifdef __GLASGOW_HASKELL__
#include "Called_stub.h"
extern void __stginit_Called(void);
#endif
#include <stdio.h>
#include <HsFFI.h>
 
int main (int argc, char * argv [])
{
char Buffer [1024];
size_t Size = sizeof (Buffer);
 
hs_init(&argc, &argv);
#ifdef __GLASGOW_HASKELL__
hs_add_root(__stginit_Called);
#endif
 
if (0 == query_hs (Buffer, &Size))
{
printf ("failed to call Query\n");
}
else
{
char * Ptr = Buffer;
while (Size-- > 0) putchar (*Ptr++);
putchar ('\n');
}
 
hs_exit();
return 0;
}
</lang>
 
The Haskell code then is pretty straightforward:
 
<lang haskell>
{-# LANGUAGE ForeignFunctionInterface #-}
 
module Called where
 
import Foreign
import Foreign.C.String (CString, withCStringLen)
import Foreign.C.Types
 
-- place a string into the buffer pointed to by ptrBuff (with size
-- pointed to by ptrSize). If successful, sets number of overwritten
-- bytes in ptrSize and returns 1, otherwise, it does nothing and
-- returns 0
query_hs :: CString -> Ptr CSize -> IO CInt
query_hs ptrBuff ptrSize = withCStringLen "Here I am"
(\(str, len) -> do
buffSize <- peek ptrSize -- check buffer size
if sizeOf str > (fromIntegral buffSize)
then do
poke ptrSize 0
return 0
else do
poke ptrSize (fromIntegral len)
copyArray ptrBuff str len
return 1)
 
foreign export ccall query_hs :: CString -> Ptr CSize -> IO CInt
</lang>
 
=={{header|HaXe}}==