我想熟悉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
test.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:CodeHaskellProjectsDevTestFFI>cabal build
Building TestFFI-0.1.0.0...
Preprocessing executable 'TestFFI' for TestFFI-0.1.0.0...
[1 of 1] Compiling Main ( srcMain.hs, distbuildTestFFITestFFI-tmpMain.o )
Linking distbuildTestFFITestFFI.exe ...
D:CodeHaskellProjectsDevTestFFI>
D:CodeHaskellProjectsDevTestFFI>distbuildTestFFITestFFI.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]
随机数据!
我做错了什么吗?我错过什么了吗?
释放内存后读取内存是未定义的行为。任何事情都是允许的——包括返回随机数据、召唤鼻魔,甚至在最无聊的情况下,返回内存被释放之前存在于内存中的数据。