What is the official way to handle a string in C ++ / FORTRAN interop

I would like to know the latest improvements in C ++ / FORTRAN compatibility when it comes to strings in particular. Below is my unsuccessful attempt, please help me fix or advise a better solution. My compiler is gcc 4.8.5

In c ++

#include <iostream> extern "C"{ void SayHello(char*); } int main(int argc, char** argv){ char * name = argv[1]; SayHello(name); return 0; } 

In fortran

 module MyModule contains subroutine SayHello(people) bind(c,name="SayHello") use, intrinsic :: iso_c_binding character, dimension(50), intent(in) :: people write(*,*) "Hello ", people end subroutine end module MyModule 
+4
source share
1 answer

Try using the c_char type:

character(kind=c_char), dimension(*), intent(in)


EDIT 1 So, after @francescalus raised the question, I looked into that further. Basically, an array of characters of "estimated size" is not needed 1 although I believe that the size of the array is char (please correct me if I'm wrong about this). I am going to post a version of C-call-Fortran below since I don’t know the C ++ syntax and don’t want it to look.


EDIT 2 As indicated in footnote 1, it is correct to declare people in Fortran as the intended dimensional array of characters or (as suggested by @VladimirF) with the size specified directly by sz . I clarified this in the code below.

Fortran Program:

 ! SayHello.f90 subroutine SayHello(people,sz) bind(c,name="SayHello") use, intrinsic :: iso_c_binding implicit none ! Notes: ! The size `sz` of the character array is passed in by value. ! Declare `people` as an assumed-size array for correctness, or just use the size `sz` passed in from C. character(kind=c_char), intent(in), dimension(sz) :: people integer(kind=c_int), intent(in), value :: sz write(*,*) "Hello, ", people(1:sz) end subroutine 

And program C:

 /*Hello.c */ #include <stdio.h> #include <string.h> #include <stdlib.h> void SayHello(char *name, int len); int main(int argc, char** argv){ size_t sz = strlen(argv[1]); char * name = malloc(sz+1); strcpy(name, argv[1]); SayHello(name, sz+1); free(name); return 0; } 

Compilation (with ifort), call and output:

 ifort /c SayHello.f90 icl Hello.c /link SayHello.obj Hello.exe MattP // output: Hello, MattP 

1 Update: it seems the official use of "for interaction" is to declare an array of characters using the estimated size: char(len=1,kind=c_char), dimension(*), intent(in) sub>

+2
source

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


All Articles