Call a function in a shared library: Difference between revisions

→‎{{header|Fortran}}: + Intel Fortran on Windows
(Added FreeBASIC)
(→‎{{header|Fortran}}: + Intel Fortran on Windows)
Line 300:
 
=={{header|Fortran}}==
===GNU Fortran on Linux===
Works on Linux with GNU gcc and gfortran 5.1.1
Line 637 ⟶ 638:
 
Finally, using C language interoperability you can call every foreign-language function in fortran if you are able to write some additional wrapper function in C language.
===Intel Fortran on Windows===
First, the DLL. Compile with '''ifort /dll dllfun.f90'''. The function is compiled with the STDCALL calling convention: it's not necessary here but it shows how to do it.
<lang fortran>function ffun(x, y)
implicit none
!DEC$ ATTRIBUTES DLLEXPORT, STDCALL, REFERENCE :: FFUN
double precision :: x, y, ffun
ffun = x + y * y
end function</lang>
 
Now, the main program. It will wait for two integers and compute the result with the DLL function. Compile with '''ifort ex_load.f90'''. Three functions of the Kernel32 library are necessary, see '''[https://msdn.microsoft.com/en-us/library/ms684175.aspx LoadLibrary]''', '''[https://msdn.microsoft.com/en-us/library/ms683212.aspx GetProcAddress]''' and '''[https://msdn.microsoft.com/en-us/library/ms683152.aspx FreeLibrary]''' in the MSDN. The DLL has to be in a directory in the PATH environment variable.
 
<lang fortran>program dynload
use kernel32
use iso_c_binding
implicit none
abstract interface
function ffun_int(x, y)
!DEC$ ATTRIBUTES STDCALL, REFERENCE :: ffun_int
double precision :: ffun_int, x, y
end function
end interface
procedure(ffun_int), pointer :: ffun_ptr
integer(c_intptr_t) :: ptr
integer(handle) :: h
integer(bool) :: status
double precision :: x, y
h = LoadLibrary("dllfun.dll" // c_null_char)
if (h == 0) error stop "Error: LoadLibrary"
ptr = GetProcAddress(h, "ffun" // c_null_char)
if (ptr == 0) error stop "Error: GetProcAddress"
call c_f_procpointer(transfer(ptr, c_null_funptr), ffun_ptr)
read *, x, y
print *, ffun_ptr(x, y)
if (FreeLibrary(h) == 0) error stop "Error: FreeLibrary"
end program</lang>
 
=={{header|FreeBASIC}}==
Anonymous user