This is the mail archive of the fortran@gcc.gnu.org mailing list for the GNU Fortran project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Returning values from C function?


--- Jeremy Cowgar <jeremy@cowgar.com> wrote:

> Quoting erik.edelmann@iki.fi <erik.edelmann@iki.fi>:
> > One thing that could go wrong is that the C
> function 'printf' expects
> > strings to be NULL terminated (i.e., it will
> continue to print characters
> > until it finds a '\0'-character).  In fortran,
> however, strings are not in
> > general NULL terminated.  Printing a string in C
> code that was passed from
> > Fortran code can therefore sometimes result in
> some extra garbage being
> > printed.
> 
> What is the proper way of passing a string to C? I
> have attempted to google
> for some good instructions on interfacing gfortran
> with C but I am failing.
> 
> Jeremy
>

here is how i do it.  this works with all F77
compilers
i am familiar with. (and gfortran!). Note the 'hidden'
argument, it contains the size of the character
variable.

as others have mentioned, fortran characters are not
null terminated.


HTH,
bud  


$ cat a.c
#include <stdio.h>
void c_print_( char x[], int len)
{
     char t[255] = {'\n'};
     int i;
     /* of course, many other ways exist in C 
        to copy the two strings.
        this should be very understandable for 
        those whose native language
        is fortran
     */ 
     for (i=0;i<len;i++)
         t[i] = x[i];
     printf(" %s %d \n",x,len);
     return;
}
$ cat a.f
       character*25,X
       data X/'hello'/
       call c_print(X)
       end

$ gcc -c -Wall a.c
$ gfortran -static a.f a.o
$ ./a.out
 hello                     25 


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]