Return an array of strings from fortran to c++

@kshores ,

If you are able to use a C++17 or later compiler, I suggest you use <string_view> if this “array” of strings is going to “live” in the Fortran side of your code. You might find it rather convenient to work with:

#include <vector>
#include <string_view>
#include <iostream>
#include "ISO_Fortran_binding.h"
using namespace std;

extern "C" {
   // Prototype for the Fortran procedures
   void Finit(void);
   void get_names( CFI_cdesc_t * );
}

int main()
{

   std::vector<std::string_view> vs;

   Finit();

   // Use macro from ISO_Fortran_binding to set aside an address to "description" of string data
   CFI_CDESC_T(1) names;

   // Call the Fortran procedure for string manipulation
   get_names((CFI_cdesc_t *)&names);

   for (int i = 0; i < names.dim[0].extent; i++) {
       vs.push_back(std::string_view((char *)names.base_addr).substr(i * names.elem_len, names.elem_len));
   }
   for (int i = 0; i < names.dim[0].extent; i++) {
       cout << vs[i] << endl;
   }

   return (0);
}
C:\temp>cl /c /std:c++20 /W3 /EHsc c++.cpp
Microsoft (R) C/C++ Optimizing Compiler Version 19.34.31937 for x64
Copyright (C) Microsoft Corporation.  All rights reserved.

c++.cpp
C:\Program Files (x86)\Intel\oneAPI\compiler\latest\windows\compiler\include\ISO_Fortran_binding.h(156): warning C4200: nonstandard extension used: zero-sized array in struct/union
C:\Program Files (x86)\Intel\oneAPI\compiler\latest\windows\compiler\include\ISO_Fortran_binding.h(156): note: This member will be ignored by a defaulted constructor or copy/move assignment operator

C:\temp>link c++.obj m.obj /subsystem:console /out:c++.exe
Microsoft (R) Incremental Linker Version 14.34.31937.0
Copyright (C) Microsoft Corporation.  All rights reserved.


C:\temp>c++.exe
red
green
blue
1 Like