This is the mail archive of the
fortran@gcc.gnu.org
mailing list for the GNU Fortran project.
Re: Returning values from C function?
On Tue, Dec 26, 2006 at 12:19:45PM -0800, Steve Kargl wrote:
> On Tue, Dec 26, 2006 at 03:05:37PM -0500, Jeremy C wrote:
> > Greetings! I am able to make this function in C:
> >
> > int hello_(int *times, char *to_who) {
> > for (int idx=0; idx<*times; idx++) {
> > printf("Hello, %s!\n", to_who);
> > }
> >
> > return 10;
> > }
>
> #include <stdio.h> /* Add missing header files. */
> int
> hello_ (int *times, char *to_who)
> {
> int idx; /* Fix warning. */
>
> for (idx = 0; idx < *xtimes; idx++)
> printf("Hello, %s!\n", to_who);
>
> return 10;
> }
>
> >
> > integer :: a
> >
> > print *, hello(10, "Me")
> >
> >
>
> program hello_me
> integer, external :: hello
> print *, hello(10, "Me")
> end program hello_me.
>
> > I get "Hello, Me!" printed on the screen 10 times as expected, but it
> > prints what seems like a pointer address.
>
> The above works for me.
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.
Erik