on master help sign in
Merge pull request #4218 from melted/paste_ffi
7664753Niklas Larsson
docs/reference/ffi.rst+15−2
@@ -217,8 +217,21 @@ global variable with the following name. The type must be just ``IO Ptr``.
217 errno : IO Ptr
217 errno : IO Ptr
218 errno = foreign FFI_C "&errno" (IO Ptr)
218 errno = foreign FFI_C "&errno" (IO Ptr)
219
219
220+If the foreign name is prefixed by a ``#``, the name is pasted in literally. This is
221+useful to access constants that are preprocessor definitions (like ``INT_MAX``).
222+
223+..code-block:: idris
224+ %include C "limits.h"
225+
226+ -- access the preprocessor definition INT_MAX
227+ intMax : IO Int
228+ intMax = foreign FFI_C "#INT_MAX" (IO Int)
229+
230+ main : IO ()
231+ main = print !intMax
232+
220−For more complicated interactions with C (such as reading and setting fields of a C struct), there is
233+For more complicated interactions with C (such as reading and setting fields
221−a module CFFI available in the contrib package.
234+of a C struct), there is a module CFFI available in the contrib package.
222
235
223FFI implementation
236FFI implementation
224------------------
237------------------
src/IRTS/CodegenC.hs+3
@@ -314,6 +314,9 @@ bcc i (TOPBASE n) = indent i ++ "TOPBASE(" ++ show n ++ ");\n"
314bcc i (BASETOP n) = indent i ++ "BASETOP(" ++ show n ++ ");\n"
314bcc i (BASETOP n) = indent i ++ "BASETOP(" ++ show n ++ ");\n"
315bcc i STOREOLD = indent i ++ "STOREOLD;\n"
315bcc i STOREOLD = indent i ++ "STOREOLD;\n"
316bcc i (OP l fn args) = indent i ++ doOp (creg l ++ " = ") fn args ++ ";\n"
316bcc i (OP l fn args) = indent i ++ doOp (creg l ++ " = ") fn args ++ ";\n"
317+bcc i (FOREIGNCALL l rty (FStr ('#':name)) [])
318+ = indent i ++
319+ c_irts (toFType rty) (creg l ++ " = ") name ++ ";\n"
317bcc i (FOREIGNCALL l rty (FStr fn@('&':name)) [])
320bcc i (FOREIGNCALL l rty (FStr fn@('&':name)) [])
318 = indent i ++
321 = indent i ++
319 c_irts (toFType rty) (creg l ++ " = ") fn ++ ";\n"
322 c_irts (toFType rty) (creg l ++ " = ") fn ++ ";\n"
test/ffi007/expected+1
@@ -7,3 +7,4 @@ After calling callback
7I'm dynamic 3
7I'm dynamic 3
86
86
97
97
10+3
test/ffi007/ffi007.h+2
@@ -1,6 +1,8 @@
1#include <stdint.h>
1#include <stdint.h>
2typedef int (*callback)(int);
2typedef int (*callback)(int);
3
3
4+#define THREE 3
5+
4int32_t testvar = 887;
6int32_t testvar = 887;
5
7
6void test_ffi(int (*cb)(int));
8void test_ffi(int (*cb)(int));
test/ffi007/ffi007.idr+6−1
@@ -42,6 +42,10 @@ test8 : IO ()
42test8 = foreign FFI_C "test_mulpar" (CFnPtr (Int -> Int -> ()) -> IO ())
42test8 = foreign FFI_C "test_mulpar" (CFnPtr (Int -> Int -> ()) -> IO ())
43 (MkCFnPtr adder)
43 (MkCFnPtr adder)
44
44
45+
46+test9 : IO Int
47+test9 = foreign FFI_C "#THREE" (IO Int)
48+
45main : IO ()
49main : IO ()
46main = do
50main = do
47 test
51 test
@@ -55,4 +59,5 @@ main = do
55 i <- test7 fptr 3
59 i <- test7 fptr 3
56 printLn i
60 printLn i
57 test8
61 test8
62+ printLn !test9
58− pure ()
63+ pure ()