【发布时间】:2015-10-21 19:19:27
【问题描述】:
我正在尝试熟悉 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 来管理内存。