【问题标题】:How do I create an interface to convert a c character array for fortran如何创建接口以将 c 字符数组转换为 fortran
【发布时间】:2013-09-26 17:23:51
【问题描述】:

我正在为 fortran 程序用 c 语言编写一个模块,我需要将一些字符串传递给 fortran 程序。我无法修改 fortran 代码,但可以编写自己的 fortran 代码来调用现有代码。我试过用谷歌搜索这个,有很多不同的方法写在我不理解的水平上。

c 字符串的长度是可变的(尽管它是在传递之前设置的)。 fortran“字符串”被声明为字符*(*),所以我看不到字符数组需要填充的长度。下面是一些代码片段,看看我需要做什么。

我正在写的c函数:

void c_func(int db_handle) {
  char *geom_name;
  int geom_handle = 0;

  size_t geom_name_len = db_get_len(db_handle); !gets the length of the name
  geom_name = (char *)malloc(sizeof(char*(geom_name_len+1)));
  db_pull(db_handle, geom_name); !pulls geom_name from db as a null terminated string
  call_fortan_function(geom_handle, geom_name); !The fortran function will set the integer
  ...}

我无法修改的 fortran 函数使用名称执行一些操作,然后为句柄设置一个值:

logical function f_fn(handle, name)

integer handle
character*(*) name

我认为最好的方法是创建一个单独的 c 函数,将 geom_name 解析为一些 fortran 将使用的内容,然后创建一个 fortran 函数来创建 fortran 字符串并将其传递给我无法使用的函数改变,但我不知道该怎么做。有什么帮助吗?

【问题讨论】:

    标签: c arrays fortran character-arrays language-interoperability


    【解决方案1】:

    您不能从 C 中可移植地调用需要 character(*) 的 Fortran 过程。这是不可能的,因为该过程通常采用另一个定义字符串长度的参数。您可能会尝试猜测它的格式,可能它是作为最后一个参数附加的int

    我会制作另一个 Fortran 包装器,它需要一个带有长度的 int 和一个长度为 length 的字符数组,最好没有尾随 \0

    logical function f_wrap(handle, name, length) bind(C,name="f_wrap")
      use iso_c_binding
      integer(c_int),value :: handle
      integer(c_int),value :: length
      character(1,kind=c_char),intent(in) :: name(length)
      character(length) :: tmp
    
      tmp = name
      f_wrap = f_fn(int(handle), tmp)
    end function
    

    tmp可能不需要,因为二进制表示是一样的,试试看吧。

    【讨论】:

      【解决方案2】:
      猜你喜欢
      • 1970-01-01
      • 2016-02-28
      • 1970-01-01
      • 1970-01-01
      • 2012-04-15
      • 2021-09-28
      • 2017-05-20
      • 2011-05-17
      • 2023-03-18
      相关资源
      最近更新 更多