on master help sign in
Prefix for pasting in identifiers in C FFI
commit3d2e39a14424f35c3fea3c50ab08141c2c15fe50 authorNiklas Larsson <niklas@mm.st> dateThu 23 Nov 2017, 19:49 (9 years ago) parentf8509e4
5 files changed+27−3
docs/reference/ffi.rst+15−2 src/IRTS/CodegenC.hs+3 test/ffi007/expected+1 test/ffi007/ffi007.h+2 test/ffi007/ffi007.idr+6−1
docs/reference/ffi.rst+15−2
@@ -217,8 +217,21 @@ global variable with the following name. The type must be just ``IO Ptr``.
217217 errno : IO Ptr
218218 errno = foreign FFI_C "&errno" (IO Ptr)
219219
220−For more complicated interactions with C (such as reading and setting fields of a C struct), there is
221−a module CFFI available in the contrib package.
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+
233+For more complicated interactions with C (such as reading and setting fields
234+of a C struct), there is a module CFFI available in the contrib package.
222235
223236FFI implementation
224237------------------
src/IRTS/CodegenC.hs+3
@@ -314,6 +314,9 @@ bcc i (TOPBASE n) = indent i ++ "TOPBASE(" ++ show n ++ ");\n"
314314bcc i (BASETOP n) = indent i ++ "BASETOP(" ++ show n ++ ");\n"
315315bcc i STOREOLD = indent i ++ "STOREOLD;\n"
316316bcc 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"
317320bcc i (FOREIGNCALL l rty (FStr fn@('&':name)) [])
318321 = indent i ++
319322 c_irts (toFType rty) (creg l ++ " = ") fn ++ ";\n"
test/ffi007/expected+1
@@ -7,3 +7,4 @@ After calling callback
77I'm dynamic 3
886
997
10+3
test/ffi007/ffi007.h+2
@@ -1,6 +1,8 @@
11#include <stdint.h>
22typedef int (*callback)(int);
33
4+#define THREE 3
5+
46int32_t testvar = 887;
57
68void test_ffi(int (*cb)(int));
test/ffi007/ffi007.idr+6−1
@@ -42,6 +42,10 @@ test8 : IO ()
4242test8 = foreign FFI_C "test_mulpar" (CFnPtr (Int -> Int -> ()) -> IO ())
4343 (MkCFnPtr adder)
4444
45+
46+test9 : IO Int
47+test9 = foreign FFI_C "#THREE" (IO Int)
48+
4549main : IO ()
4650main = do
4751 test
@@ -55,4 +59,5 @@ main = do
5559 i <- test7 fptr 3
5660 printLn i
5761 test8
58− pure ()
62+ printLn !test9
63+ pure ()