dram.me

将Fortran字符串传入C的几种方式

在C中,字符串可以理解为数组,也可以看作指针,所以对应的在Fortran中也可以基于这两种模式将字符串传入C。

以下代码中,c_print_v1是作为字符数组处理,c_print_v2作为数值数组处理,而c_print_v3则是作为指针处理。

program main
  implicit none

  interface
     subroutine c_print_v1(string) bind(c, name='print')
       use iso_c_binding, only: c_char
       character(kind=c_char), intent(in) :: string (*)
     end subroutine c_print_v1

     subroutine c_print_v2(string) bind(c, name='print')
       use iso_c_binding, only: c_signed_char
       integer(c_signed_char), intent(in) :: string (*)
     end subroutine c_print_v2

     subroutine c_print_v3(string) bind(c, name='print')
       use iso_c_binding, only: c_ptr
       type(c_ptr), value :: string
     end subroutine c_print_v3
  end interface

  block
    use iso_c_binding, only: c_char, c_loc, c_null_char, c_signed_char

    character(4, c_char),   target :: s1     = c_char_'abc' // c_null_char
    integer(c_signed_char), target :: s2 (4) = (/ 97, 98, 99, 0 /)

    call c_print_v1(c_char_'abc' // c_null_char)
    call c_print_v1(s1)
    call c_print_v3(c_loc(s1))
    call c_print_v2(s2)
    call c_print_v3(c_loc(s2))

  end block
end program main

对应的C代码如下:

#include <stdio.h>

void print(char const *s)
{
	puts(s);
}