Re: How to call Fortran functions from LuaJIT

  • From: Pedro Tabacof <tabacof@xxxxxxxxx>
  • To: luajit@xxxxxxxxxxxxx
  • Date: Fri, 28 Nov 2014 09:39:43 -0200

Hello Ciprian,

Thank you very much for the step by step explanantion! As a new user, this
will be very helpful indeed (and I believe even more experienced users will
benefit from the knowledge that Fortran is as easy to interface as C).

Pedro.

On Thu, Nov 27, 2014 at 9:00 PM, Ciprian Tomoiaga <
ciprian.tomoiaga@xxxxxxxxx> wrote:

> Hi Pedro,
>
> Yes, it is possible without having to go through C. First, you have to
> compile the fortran. I use gfortran:
>   gfortran -O3 -shared -fPIC your_file.f -o libyour_file.so
>
> The flags -shared and -fPIC are important to make it loadable.
>
> Then, in LuaJIT you define the functions as you would do in C, like the
> article you pointed describes.
>
> Example:
> if in Fortran you have:
> ----------------------------------------
> subroutine init(p1,p2,p3)
> implicit none
> integer p1,p2
> double precision p3
> ........
> ----------------------------------------
>
>
> Then in LuaJIT you would have:
> --------------------------------------------
> local ffi = require'ffi'
> local mylib = ffi.load("path/to/libmy_file.so")
>
> ffi.cdef [[
>   void init_(int *p1, int *p2, double *p3);
> ]]
>
> -- You need pointers to the raw types, which in this case can be
> represented as an array of size 1
> local p1, p2, p3 = ffi.new("int[1]"), ffi.new("int[1]"),
> ffi.new("double[1]")
>
> -- say p1, p2 are input params and p3 output; set p1, p2 to desired values
> p1[0] = 2
> p2[0] = 3
>
> -- call your function
> mylib.init(p1, p2, p3)
>
> -- now you have the result in p3, which is a 'pointer'
> if p3[0] ~= 0 then
>   -- ...
>
>
> This is how we've been using it. If anyone has suggestions, please, they
> are more than welcome.
>
> P.S. You should declare your 'pointer' types once, and use them as
> constructors:
> local int_p = ffi.typeof("int[1]")
> local p1 = int_p()
>
>
> Best regards,
> Ciprian
>
> --
> Ciprian *Tom*oiaga
>
>
> On 27 November 2014 at 17:58, Pedro Tabacof <tabacof@xxxxxxxxx> wrote:
>
>> Hello,
>>
>> I'd like to know how to use the FFI to call a function from a Fortran 77
>> code. One way I see is to translate the code to C using f2c, but this is
>> far from ideal.
>>
>> Calling Fortran from C code is simple, but you need to compile the o
>> bject file using a Fortran compiler such as gfortran (see
>> http://www.xgear.eu/callfortranfromc.html).
>>
>> Is there an easy way to do this from LuaJIT?
>>
>> Thank you,
>> Pedro.
>>
>> --
>> Pedro Tabacof
>>
>
>


-- 
Pedro Tabacof

Other related posts: