How to call Fortran routine with unit number argument from C - c

If I have a Fortran subroutine which takes a Fortran IO Unit as one of its parameters (for printing debug information to), and this function is compiled into a shared library, how do I correctly call this function from C?
! An example subroutine that I want to call from C:
subroutine hi(unit)
integer :: unit
write(unit,*) "hello"
end subroutine
! example call site in Fortran
program main
call hi(6)
end
I am interested in how these unit numbers relate to file descriptors.

This is completely compiler dependent, there is no portable correspondence. See the manual of your compiler if they support some sort of interoperability as an extension.

Related

Can C program be used without main function?

From a Fortran Code, I intend to run a C code (to read a file) and fetch the read information.
The main program is the Fortran code, which uses a function written in C to do the processing.
In this C code, is it necessary to run a main function?
If Fortran only calls the C function, then the C code does not need a main() function.
The main() function of C is the program entry point. The system loads the .exe, transfers control to the startup code, which address is mentioned in the .exe file (the startup code is called crt, C run-time start-up). The run-time startup does initialization and then transfers control to the user code. The user code entry point is main().
Since Fortran is the main program, no C run-time start-up is needed and so no main() is needed.
No, you don't need a main in your C code. The linker will use the main from the FORTRAN code, or rather, the FORTRAN equivalent of main, when linking your C functions to the FORTRAN program.

Out of order print statements when using fortran program to call c subroutine

I am experiencing problems with displaying values on the console while invoking a C subroutine from a fortran subroutine. I have print statements immediately before and after the call to the C subroutine, as well as a print statement within the C subroutine. However, upon executing the program, the C statements are printed before the two Fortran statements, rather than between them. I’ve looked thoroughly within the code, and there are no calls to the C subroutine elsewhere, so there is no obvious reason why the c statement should be printed before the Fortran statement. I created a simpler Fortran-C program (below) to try to reproduce the problem, but the code executed the print statements in the expected order. I wonder if someone has any insights as to what could be the problem. Thank you.
Sample Fortran code:
program test
print *, 'Calling C program'
call cprog()
print *, 'Finished calling C program.'
end program test
sample c code to be invoked from fortran:
void cprog()
{
printf("THIS IS A TEST\n");
return;
}
Output:
Calling C program
THIS IS A TEST
Finished calling C program.
Output similar to what I’m experiencing with more complex code:
THIS IS A TEST
Calling C program
Finished calling C program
The behaviour of mixed language input or output to the same external unit (~file) is processor dependent - see F2008 15.5.1p6. Amongst other things, this is to accommodate the possibility of buffering (or outright incompatibility) in the runtime support for each language. Because the behaviour is processor dependent there is no guarantee of any particular order.
The robust solution is to do all the input/output to that particular file from the one language, perhaps by providing a procedure/function that the other language can call to do input/output.

how to link main and subprograms in Fortran95?

How to link an external subroutine to the main program in Fortran?
Although, I got an answer from the book with the title of "Fortran 90 for scientists and engineers"
as following:
Note also that, since an external subprogram resides in a separate
file from the main program, it must be compiled separately. Under
FTN90 an intermediate type of machine code, called relocatable binary
is produced in a file with the .OBJ extension. This in turn must be
linked with the calling program by means of a special program called a
linker, finally resulting in a .EXE version of the main program. Your
compiler manual will have the details of how to do this. Once it is
finally debugged, an external subprogram need never be recompiled,
only linked. This prevents you from wasting time in compiling it over
and over, which would be the case if it was an internal subprogram.
Anyway I did not find any manual for how to link the main and subroutine programs. I use Silverfrost (Plato) to debug and run the programs. Besides, I have installed the "Intel Parallel Studio XE 2011" on the system.
For the time being I am going to assume that the external subprogram (function or subroutine) is in the same directory as the main program. In the days of fortran77 or earlier you would just call the subroutine from the main program and link them with a COMMON statement that existed both in the main program and the subprogram. However, now days the preferred method is to write your external subprograms into modules and link the module with a USE statement. For example lets make up a fictional subprogram that read in a value of 'x' and worked on it to feed back values of 'y' and 'z' to the main program. The program and module might look like the example below. A Module in essence i fortran attempt at becoming somewhat object oriented as it ensures that data is encapsulated to the programs and is not globally accessible unless the programmer wants it to be global. It is important that the programmer declare a subprogram as PRIVATE, if it is only to be called by other programs in the module and PUBLIC if it is to be called by the main program. Also in order to ensure that data is used properly, you should declare it as INTENT(IN), INTENT(OUT) or INTENT(INOUT) if the variable is only being fed into the routine, out of the routine or will be called tot he routine, worked on and fed back to the main program. I hope this helped, if not feel free to ask any other questions. Also when compiling a main program with external subprograms call them in order of subprograms to program. This means do not use ifort main.f90 module.f90, instead you must type fort module.f90 main.f90 assuming you are using an intel compiler, if not then replace fort with whatever command is used for your compiler.
PROGRAM MAIN
USE Test
IMPLICIT NONE
REAL :: X,Y,Z
X = 5.0
WRITE(*,*) X,Y,Z
END PROGRAM MAIN
MODULE Test
PUBLIC :: Subroutine_Example
CONTAINS
SUBROUTINE Subroutine_Example(X,Y,Z)
REAL, INTENT(IN) :: X
REAL, INTENT(OUT :: Y,Z
Y = X + 34.6
Z = X - 1.4
END Subroutine_Example
END MODULE Test

How to use Fortran shared library in C program?

I have put several subroutines into .f95 file, compiled it withgfortran -shared -fPIC -o bin/Debug/libpr10.so main.f95, now I want to use some of subroutines from that library in my C program. How do I do that (syntactically)? Do I have to produce any "headers" in Fortran library where I should declare the subroutines I want to use outside of the library (as I would have to if it was C)?
If I just tell the linker where the library is and try to call any subroutines in main() i get an error
UPDATE I don't want to mix fortran and C! I just want to use one subroutine from Fortran shared library, even w/o arguments. Despite that I have pointed out a path to the .so library, it's "invisible" for C program! The question is how to tell C program that there actually IS a subroutine that I want to invoke.
If I'm violently mistaken with "mixing" idea, correct me.
Ok, I don't think that this solution is universal but for Microsoft Visual Studio it should be __stdcall before subroutne name, and for gcc it should be a _ symbol after subroutine name e.g. we want to call subroutine called menu, so we put menu_(); into main function.

Fortran interface to call a C function that return a pointer

I have a C function,
double* foofunc()
{
/* Function Body */
}
I don't know how to declare an interface in Fortran to call this C function.
Also if a pointer is supposed to be pointing to GPU device memory, how could I define that in the Fortran interface? Do I need to use DEVICE attribute.
Please use features supported by Fortran up to 2003.
Any suggestions?
Since you have Fortran 2003, the easy way to interface Fortran and C is to use the ISO C Binding. (Most Fortran 95 compilers now support the ISO C Binding, even if they aren't full Fortran 2003 compilers.) This is far, far better than the complicated methods suggested in an earlier answer, which were necessary in an earlier era -- it is part of the language and therefore portable, and compiler and platform independent. But the Fortran 2003 version doesn't cover ever possibility. (The next Fortran will add additional cases of interfacing to C.) You can easily pass an argument that is a C pointer -- just leave off the "value" atttribute in the Fortran declaration. A pointer to a pointer needs C_PTR. I don't know about a pointer as a function return... I will have to experiment when I have time. If you have to, make a trivial C glue routine that converts the pointer of the function return into an argument -- that case is easy.
Re a pointer to GPU device memory -- unless your compiler has a non-standard feature, it won't have "DEVICE". Perhaps "volatile" will help? Create an appropriate user-defined type...
There are examples in the gfortran manual under "Interoperability with C". Since this is part of the language, this documentation should help even if you aren't using gfortran.
As M. S. B. said, using the fortran 2003 C interoperability features is easiest.
Simply declare the function result as type(c_ptr), and transform it to a fortran pointer by calling c_f_pointer.
The following simple example works when compiled with:
gfortran foo.f03 foofunc.c -o foo.exe
(gfortran version 4.5.0)
Contents of foo.f03:
program foo
use, intrinsic :: iso_c_binding, only : c_ptr, &
c_f_pointer, &
c_double
implicit none
type(c_ptr) :: c_p
real(c_double), pointer :: f_p
interface
function foofunc() bind(c)
import :: c_ptr
implicit none
type(c_ptr) :: foofunc
end function foofunc
end interface
c_p = foofunc()
call c_f_pointer(c_p, f_p)
print *, f_p
end program foo
Contents of foofunc.c:
double bar = 2;
double *foofunc()
{
return &bar;
}
I don't know how well it will work with a pointer to GPU device memory, though. Never dealt with that.
You want to call a C function from Fortran Program. There are many ways.
One way is to translate the C routine to fortran. If your C program is long, complex, and well tested then it may not be easy option for you. The other way is to convert the fortran to C. There may be similar problem to you.
If you can not skirt the problem as above, then you have to face the problem as below.
In programming parlance it is called Mixed Language Programming.
I do not know what version of which language and OS U are using. So instead of giving a ready made solution I shall give you four alternative approaches below. I have used all in implemented applications. The first two are for those lucky having a powerful OS ( a rare commodity now ). The program runs fast in both and suitable for hard real time jobs. The last two are for any OS, but program runs slow, particularly if C routine is called frequently. You also have to do little more programming work in all approaches. Be also aware that your C function returns a pointer in each of the alternatives.
Some fortran compilers ( not all ) allow calling a non-fortran function. This requires appropriate facilities in the OS where both fortran and C are running. In such cases identical stack management is used during procedure call. Read the programmers manual of both languages and code appropriately.
If this is not possible then you can trick the OS to do so but you need an intermediate function written in Assembler. You call assembler routine from fortran and then call the C routine from assembler and return in reverse manner. You need to know stack management details of all three that is of Fortran, Assembler and C and write a code for translating fortran stack to C stack. This will be in the assembler routine.
In both above approaches you have to be aware how your Linker ( or Binder ) works and you may have to do some extra job there. In either case it will be same .exe file so your program will run fast. In such OS’s any languages, strange to each other, can be mixed. Even DLL’s can be used. Only complexity comes if the run time library uses a fortran function having same name as a C function but doing different jobs. An OS supporting mixed language programming generally gives you some tools of preventing this.
If above alternatives are not feasible, then make both fortran and C programs as separate .exe and run both as two concurrent processes. ( note they can be in same computer or in different computers under different OS even ! ). Now whenever you need to call C from fortran, pass all parameters and data though any interprocess communication mechanism available to you, say pipe, socket or whatever it is. The C program can return data by similar mechanism. Be sure to add appropriate code for handling parameter passing through interprocess communication. Synchronisation of two processes and distinguishing old data from recent data is also your job. Stack management is not required.
This one is for those who dislike stack, synchronization, linker or anything that requires intelligence. Programs will run slowest if the C program has to be called frequently. Counter-intuitively, if the C program has to be called once only, then this becomes most intelligent solution too! Output data from fortran program to disk ( flat file or data-base ). Then call the C program to read from same file and return data to fortran in same manner. Be careful about closing the file before change of language. Handle all errors in file input-output calls. Else you crash.

Resources