我試圖讓熟悉Haskell的FFI,所以我寫了這個小例子:功能「免費」上Haskell的FFI似乎並沒有工作
Main.hs:
{-# LANGUAGE ForeignFunctionInterface #-}
import Foreign.C.Types
import Foreign.Ptr (Ptr)
import Foreign.Marshal.Array (peekArray)
import Foreign.Marshal.Alloc (free)
foreign import ccall "test.h test"
test :: CInt -> Ptr CInt
main = do
let rval = test 6
-- print the array
list <- peekArray 6 rval >>= return . map toInteger
putStrLn $ show list
free rval
-- print it again (it should okay)
putStrLn $ show list
-- try to retrieve it AGAIN after I used free. Should print random values
peekArray 6 rval >>= return . map toInteger >>= putStrLn . show
測試。^h
#ifndef TEST_H
#define TEST_H
int* test(int a);
#endif
test.c的
#include "test.h"
#include <stdio.h>
#include <stdlib.h>
int* test(int a)
{
int* r_val = (int*)malloc(a * sizeof(int));
r_val[0] = 1;
r_val[1] = 2;
r_val[2] = 3;
r_val[3] = 4;
r_val[4] = 5;
r_val[5] = 6;
return r_val;
}
,當我編譯和運行Main.hs
我得到的輸出是:
D:\Code\Haskell\Projects\Dev\TestFFI>cabal build
Building TestFFI-0.1.0.0...
Preprocessing executable 'TestFFI' for TestFFI-0.1.0.0...
[1 of 1] Compiling Main (src\Main.hs, dist\build\TestFFI\TestFFI-tmp\Main.o)
Linking dist\build\TestFFI\TestFFI.exe ...
D:\Code\Haskell\Projects\Dev\TestFFI>
D:\Code\Haskell\Projects\Dev\TestFFI>dist\build\TestFFI\TestFFI.exe
[1,2,3,4,5,6]
[1,2,3,4,5,6]
[1,2,3,4,5,6]
似乎也沒有任何意義了我。我第三次打印陣列時,我期待着這樣的事:
[69128391783,2083719073,934857983457,98374293874,0239823947,2390847289347]
隨機數據!
我做錯了什麼?我錯過了什麼嗎?
爲什麼你認爲釋放的內存應該改變?請注意,Haskell運行時不使用malloc/free來管理內存。 – ErikR