This is the mail archive of the
fortran@gcc.gnu.org
mailing list for the GNU Fortran project.
Re: Returning values from C function?
- From: Bud Davis <bdavis9659 at sbcglobal dot net>
- To: Jeremy Cowgar <jeremy at cowgar dot com>, fortran at gcc dot gnu dot org
- Date: Tue, 26 Dec 2006 17:38:10 -0800 (PST)
- Subject: Re: Returning values from C function?
- Domainkey-signature: a=rsa-sha1; q=dns; c=nofws; s=s1024; d=sbcglobal.net; h=X-YMail-OSG:Received:Date:From:Subject:To:In-Reply-To:MIME-Version:Content-Type:Content-Transfer-Encoding:Message-ID; b=J4mwCJom2IIqwUSnpIX8t0c5m7URk73EwLQJKHHPkJOAC4/dtFCOjtF3/t0/pnWKc9RHw3iJz2Hmdpnyz5iMrDBXpY1dPRNEB7aHlcaXIXkY33vrMG/Gqsx/e1ABKVjCGde/3wlefBymuoBjycwphb07IiFH5ugXiCjpES8cdbQ=;
--- 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