First, the main reference is the thread Linking FORTRAN with Librarylink, which teaches how to make the link between a FORTRAN subroutine and a Mathematica code, by using Librarylink. This must done through a C code, from where the FORTRAN subroutine is called. The C code is, then, compiled via Mathematica.
I have studied the examples and tried them myself. My doubt is on how to load FORTRAN libraries, e.g. for using the FORTRAN command open within the subroutine. Whenever I try to call a subroutine that contains open, I read an error message on the screen. Read below my minimal example.
FORTRAN subroutine
The subroutine reads a,b,c and stores a+b+c into the variable sum. Additionally it open,reads and close file.dat.
!fadd.f90
subroutine add(a,b,c,sum)
implicit none
integer a,b,c,sum
sum=a+b+c
open(1,file='file.dat')
read(1,*)
close(1)
return
end subroutine
file.dat only contains the number 1, for the minimal example. This value is not used anywhere, for simplification. My actual code would use dat files to make complicated computations.
Calling the subroutine from C
//MMA.cc
//Link directly to fortran object file
#include "WolframLibrary.h"
DLLEXPORT mint WolframLibrary_getVersion(){
return WolframLibraryVersion;}
DLLEXPORT int WolframLibrary_initialize(WolframLibraryData libData){
return 0;}
//declare fortran subroutine
extern "C" { void add_(mint* a, mint* b, mint* c, mint* sum);}
EXTERN_C DLLEXPORT int add(WolframLibraryData libData, mint Argc, MArgument *Args, MArgument Res){
mint I0 = MArgument_getInteger(Args[0]);
mint I1 = MArgument_getInteger(Args[1]);
mint I2 = MArgument_getInteger(Args[2]);
mint sum;
add_(&I0,&I1,&I2,&sum);//call fortran subroutine
MArgument_setInteger(Res,sum);
return LIBRARY_NO_ERROR;
}
Mathematica: create library and load library function
Needs["CCompilerDriver`"];
CreateLibrary[{"MMA.cc", "fadd.o"}, "myadd", "Debug" -> True, "TargetDirectory" -> "."]
funcadd = LibraryFunctionLoad["./myadd", "add", {Integer, Integer, Integer}, Integer]
Print[ funcadd[2,2,2] ]
Exit[]
ERROR (Running Mathematica 8 through Linux terminal)
(* /optifi/Wolfram/Mathematica/8.0.4/SystemFiles/Kernel/Binaries/Linux-x86-64/MathKernel: symbol lookup error: (...)/myadd.so: undefined symbol: _gfortran_st_open *)
For compiling the FORTRAN code, I have run on LINUX terminal
gfortran -c -fPIC fadd.f90
where -fPIC has been added as requested by an error message telling recompile with -fPIC.