Passing strings for execution in Fortran subroutin

2019-01-15 11:11发布

问题:

In the following subroutine I would like to pass a string variables named str. If it is 'poly', 'gaus', 'slat', then it has a predefined action (fval = see code below ). I would like to have the user specify a function to use and pass that as a string variable.

That is ...

If str = '3*cos(i*t)', then i would like to have fval be equal to 3*cos(i*t). How can I get Fortran to interpret the string entered as a command to be executed by Fortran?

subroutine f(fval, i, t, str)
implicit none
integer, parameter :: ikind = selected_int_kind(8)
integer, parameter :: dbl = selected_real_kind(15,307)

integer(kind = ikind) :: i
real(kind = dbl) :: fval, t
character str*100

if(str .eq. 'poly') then
    fval = t**i
elseif(str .eq. 'slat') then
    fval = exp(-i*t)
elseif(str .eq. 'gaus') then
    fval = exp(-i*t*t)
else
    fval = ???
endif

end subroutine

回答1:

you can't. not easily. there are two things you can do, though:

  • first, you can use function pointers. there's a simple example at http://www.macresearch.org/advanced_fortran_90_callbacks_with_the_transfer_function - the idea is that you can pass the name of a function defined elsewhere. that may be enough to solve your problem.

  • you can call a library that parses the string and evaluates the expression. i don't know of anything in fortran, but your fortran compiler may support calling c routines. for gfortran (and maybe others), this looks like it would work - http://www.gnu.org/s/libmatheval/ (example fortran code at http://www.gnu.org/s/libmatheval/manual/libmatheval.html#Fortran-sample-program)



回答2:

Actually, it's really simple

subroutine f(fval, i, t, str) ... character(len=*), intent(in) :: str ... end subroutine

The trick is to define the dummy string argument as of "unknown length" BUT with the intent(in) modifier.