传递字符串以在 Fortran 子例程中执行 [英] Passing strings for execution in Fortran subroutines

查看:23
本文介绍了传递字符串以在 Fortran 子例程中执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的子程序中,我想传递一个名为 str 的字符串变量.如果是'poly''gaus''slat',那么它有一个预定义的动作(fval =见下面的代码).我想让用户指定要使用的函数并将其作为字符串变量传递.

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.

那是……

如果 str = '3*cos(i*t)',那么我希望 fval 等于 3*cos(i*t).如何让 Fortran 将输入的字符串解释为由 Fortran 执行的命令?

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

推荐答案

你不能.不容易.不过,您可以做两件事:

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.

您可以调用一个库来解析字符串并计算表达式.我不知道 fortran 中的任何内容,但是您的 fortran 编译器可能支持调用 c 例程.对于 gfortran(也许还有其他人),这看起来会起作用 - http://www.gnu.org/s/libmatheval/ (http://www.gnu.org/s/libmatheval/manual/libmatheval.html#Fortran-sample-program)

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)

这篇关于传递字符串以在 Fortran 子例程中执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆