1

The idris2 has the following example for FFI, which adds two integers in C:

#include <stdio.h>

int add(int x, int y) {
    return x+y;
}

(small.c)

I followed the steps, and after linking:

gcc -shared smallc.c -o libsmall.so

and indeed the foreign function add can be called as shown in the example:

%foreign "C:add,libsmall"
add : Int -> Int -> Int

main : IO ()
main = printLn (add 70 24)

:exec main gives 94.

However, if I just evaluate this foreign function as a pure function (add 70 24), then the idris2 REPL does not compute anything, and just echoes back the expression:

add 70 24
add 70 24

So, the pure foreign function only computes inside the IO() valued function when :exec. This is not consistent with what the same documentation claims:

It is up to the programmer to declare which functions are pure, and which have side effects, via PrimIO

In contrast, (+) 70 24 evaluates correctly in the REPL.

(+) 70 24
94

(The above is tested with idris2 0.6.0 under Ubuntu 22.04 LTS.)

My questions are:

How to fix the above example so that the foreign function evaluates as a stand-alone expression?

Why did the builtin pure functions such as (+) work? Is it because they use RefC or some different methods?

Related:

How to write a pure String to String function in Haskell FFI to C++

How to read a C/C++ array from idris2 FFI?

thor
  • 21,418
  • 31
  • 87
  • 173

0 Answers0