Есть такой код на С:
#include <malloc.h>
struct arr{
int **arr;
int maxI;
int maxJ;
};
typedef struct arr Arr;
Arr *newArr(int i, int j){
Arr *a = malloc(sizeof(Arr));
a -> arr = malloc(sizeof(int*) * i);
a -> maxI = i;
a -> maxJ = j;
for(int n; n<i; ++n){
a -> arr[n] = malloc(sizeof(int) * j);
}
return a;
}
void freeArr(Arr *a){
for(int i=0; i<a -> maxI; ++i)
free(a -> arr[i]);
free(a -> arr);
free(a);
}
int peekArr(Arr *a, int i, int j){
/* printf(":%Ld: %d %d %d %d\n",(long long)(a -> arr),a -> maxI, a -> maxJ, i, j);
fflush(stdout);
printf("> %d\n", a -> arr[i][j]);
fflush(stdout);*/
return a -> arr[i][j];
}
void pokeArr(Arr *a, int i, int j, int v){
a -> arr[i][j] = v;
}
int maxI(Arr *a){
return a -> maxI;
}
int maxJ(Arr *a){
return a -> maxJ;
}
{-# INCLUDE "struct.c" #-}
{-# LANGUAGE ForeignFunctionInterface #-}
import Foreign.C
import Foreign.Ptr
foreign import ccall unsafe "newArr" c_newArr :: CInt -> CInt -> IO (Ptr ())
foreign import ccall unsafe "freeArr" c_freeArr :: Ptr () -> IO()
foreign import ccall unsafe "maxI" c_maxI :: Ptr () -> CInt
foreign import ccall unsafe "maxJ" c_maxJ :: Ptr () -> CInt
foreign import ccall unsafe "peekArr" c_peekArr :: Ptr () -> CInt -> CInt -> IO CInt
foreign import ccall unsafe "pokeArr" c_pokeArr :: Ptr () -> CInt -> CInt -> CInt -> IO()
newtype IArr2 = IA (Ptr ())
newArr :: Int -> Int -> IO IArr2
newArr maxI maxJ = fmap IA $ c_newArr (fromIntegral maxI) (fromIntegral maxJ)
freeArr :: IArr2 -> IO()
freeArr (IA a) = c_freeArr a
maxI :: IArr2 -> Int
maxI (IA a) = fromIntegral$ c_maxI a
maxJ :: IArr2 -> Int
maxJ (IA a) = fromIntegral$ c_maxJ a
peekArr :: IArr2 -> Int -> Int -> IO Int
peekArr (IA a) i j = fmap fromIntegral $ c_peekArr a (fromIntegral i) (fromIntegral j)
pokeArr :: IArr2 -> Int -> Int -> Int -> IO()
pokeArr (IA a) i j v = c_pokeArr a (fromIntegral i) (fromIntegral j) (fromIntegral v)
main = do
a <- newArr 4 6
print (maxI a, maxJ a)
peekArr a 0 0 >>= print
mapM_ (\(i,j) -> pokeArr a i j 0) [(x,y) | x <- [0..3], y <- [0..5]]
pokeArr a 0 0 1
pokeArr a 3 2 2
flip mapM_ [0..3] $ \i -> do
mapM_ (\j -> peekArr a i j >>= putStr.( ++ " ").show) [0..5]
putChar '\n'
freeArr a