on master help sign in
Make type of `withAlloc` more general
b927dd4Alex Queiroz
libs/contrib/CFFI/Memory.idr+3−2
@@ -40,10 +40,11 @@ free : CPtr -> IO ()
40free (CPt p _ ) = mfree p
40free (CPt p _ ) = mfree p
41
41
42||| Perform an IO action with memory that is freed afterwards
42||| Perform an IO action with memory that is freed afterwards
43−withAlloc : Composite -> (CPtr -> IO ()) -> IO ()
43+withAlloc : Composite -> (CPtr -> IO a) -> IO a
44withAlloc t f = do m <- alloc t
44withAlloc t f = do m <- alloc t
45− f m
45+ r <- f m
46 free m
46 free m
47+ pure r
47
48
48infixl 1 ~~>
49infixl 1 ~~>
49||| Perform an IO action with memory that is freed afterwards
50||| Perform an IO action with memory that is freed afterwards
test/ffi008/ffi008.c+12−1
@@ -1,5 +1,7 @@
1−#include "ffi008.h"
2#include <stdio.h>
1#include <stdio.h>
2+#include <stdlib.h>
3+
4+#include "ffi008.h"
3
5
4int size1(void) {
6int size1(void) {
5 return sizeof(struct test1);
7 return sizeof(struct test1);
@@ -12,3 +14,12 @@ int size2(void) {
12void print_mystruct(void) {
14void print_mystruct(void) {
13 printf("a: %d b: %d\n", mystruct.a, mystruct.b);
15 printf("a: %d b: %d\n", mystruct.a, mystruct.b);
14}
16}
17+
18+struct test2* calc_struct(struct test1 *in)
19+{
20+ struct test2 *out = malloc(sizeof(struct test2));
21+ out->a = in->a * in->a;
22+ out->b = in->b & 0x0000FFFF;
23+
24+ return out;
25+}
test/ffi008/ffi008.h+2
@@ -15,3 +15,5 @@ struct test2 mystruct;
15int size1(void);
15int size1(void);
16int size2(void);
16int size2(void);
17void print_mystruct();
17void print_mystruct();
18+
19+struct test2* calc_struct(struct test1*);
test/ffi008/ffi008.idr+10
@@ -18,6 +18,9 @@ mystruct = foreign FFI_C "&mystruct" (IO Ptr)
18print_mystruct : IO ()
18print_mystruct : IO ()
19print_mystruct = foreign FFI_C "print_mystruct" (IO ())
19print_mystruct = foreign FFI_C "print_mystruct" (IO ())
20
20
21+calc_struct : Ptr -> IO Ptr
22+calc_struct = foreign FFI_C "calc_struct" (Ptr -> IO Ptr)
23+
21test1 : Composite
24test1 : Composite
22test1 = STRUCT [I8, I64]
25test1 = STRUCT [I8, I64]
23
26
@@ -46,3 +49,10 @@ main = do
46 print !(peek I32 f1)
49 print !(peek I32 f1)
47 withAlloc PTR $ \p =>
50 withAlloc PTR $ \p =>
48 poke PTR p fms
51 poke PTR p fms
52+ res <- withAlloc test1 $ \p => do
53+ let f1 = (test1 # 0) p
54+ let f2 = (test1 # 1) p
55+ poke I8 f1 42
56+ poke I64 f2 1125899906842624
57+ calc_struct p
58+ free res