The correct way to pass a string from Fortran to C/C++

Viewed 3194

I want to pass a string from Fortran to C/C++. Here is my Fortran code:

subroutine zdplaskinGetSpeciesName(cstring, index) bind(C, name='zdplaskinGetSpeciesName')
  use iso_c_binding
  use ZDPlasKin
  implicit none
  integer, intent(in) :: index
  CHARACTER(10), TARGET :: fstring = ''
  TYPE(C_PTR) :: cstring
  fstring = species_name(index+1)
  cstring = c_loc(fstring)
end subroutine zdplaskinGetSpeciesName

ZDPlasKin is a module which has species_name(i).

extern "C" void zdplaskinGetSpeciesName(char* cstring[], size_t* index);
char* cstring[1];
size_t index = 1;
zdplaskinGetSpeciesName(cstring, &index);
string speciesName = string(cstring[0]);
cout << speciesName << endl;

The output seems to be fine for this method. However, I want to trim the trailing space (character(10) gives extra space), so my C++ code can read the string correctly. I tried another way.

subroutine zdplaskinGetSpeciesName(cstring, index) bind(C, name='zdplaskinGetSpeciesName')
  use iso_c_binding
  use ZDPlasKin
  implicit none
  integer, intent(in) :: index
  CHARACTER(:), allocatable, TARGET :: fstring
  TYPE(C_PTR) :: cstring
  fstring = trim(species_name(index+1))
  cstring = c_loc(fstring)
end subroutine zdplaskinGetSpeciesName

But this way I got some weird symbols.


I want to do things correctly so I don't need to worry later. Memory leak is not what I want. So I think I will try the alternative way you suggested. I think I would like to know is how can I know if I need to deallocate a pointer. Here is another code I found on StackOverflow (Although this one passes C++ string to Fortran. https://stackoverflow.com/a/30430656/721644)

Do you think this is okay to use? Or there might be memory leak. Also can you give me some hint about the alternative way you suggested?

2 Answers
Related