Assigning an Array of Characters to Fortran

I need to write a routine that can be called by both C and Fortran. This routine takes a file name as one of its arguments. I know that for convenient interaction with C, ISO C binding recommends using character arrays for interaction.

I have a question: is there such a thing as a literal array of characters that is easy to write? I have a routine like this:

subroutine my_sub(char_array)
  use iso_c_binding, only: c_char
  char(kind=c_char, len=1), dimension(:), intent(in) :: char_array
  ...
end subroutine my_sub

Is it possible to call this with something like:

call my_sub('Hello World!')

Or I need to do something terrible, like:

call my_sub((/ 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!' /))

My main problem is that she does not like the array of the intended form, and that giving it a large (large) size also displays all the garbage memory, which, as it turns out, subsequently appears.

Is there a better way to do this?

+4
2

.

call my_sub('Hello World!')

dimension(*) .

, Fortran 2008 C- . , .

. iso_c_binding C-. bind(C), , . . ( ). 1- .

" iso_c_binding ".

Fortran.

+4

. .

program string0
  implicit none
  character, allocatable :: string(:)
  character(len = :), allocatable :: text

  text = 'this is a pen'
  string = transfer(text, ' ', size = len_trim(text))
  string = achar(iachar(string) - 32)
  text = transfer(string, text)
  print *, text

  stop
end program string0
+3

Source: https://habr.com/ru/post/1531631/


All Articles