This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC 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: calling C function from program.


Hi Ganesh,

 I seem to recall, fortran char strings as having an implicit
length field. C char strings have an implicit '\0' at the end.
The C functions for string manipulation assume '\0' terminated
strings, so you have to provide it with that.
 The results, you are seeing, are due to the compiler placing
the fortran string next to each other in memory, as in
"calling C programhai". Had these been C style strings, they
would look like "calling C program\0hai\0". the only reason,
printf actually stops after printing hai is, that the next
byte happens to be a \0 due to the physical layout of your
program. It could potentially have kept reading garbage values
from memory, until it found a \0 or segfaulted.

Yours sincerely,

bjorn

Ganesh Ramakrishnan wrote:
> 
> sir/madam,
>              I am facing some problem, when i call a C
> function from a fortran program & compile it using
> g77.
> 
> Here is my fortran program ---->
> ------------------------------------------------------
>       program hello
>       call callC("calling C program")
>       print *, "hai"
>       end
> -------------------------------------------------------
> Here is my C function ---------->
> -------------------------------------------------------
>       callC_(x)
>       char* x;
>        {
>          printf("%s\n", x);
>        }
> ----------------------------------------------------
> Now if i compile this with g77, I am getting the
> output like this
>  -----------------------------------------------------
>      calling C programhai
>      hai
> ------------------------------------------------------
>   The argument which i am passing to the C
> function("calling C program") is appended with the
> output of the next 'print' statement("hai"). if i
> append '\0' at the end of that argument("calling C
> program\0"), then it is working fine. Why is it like
> this.
>  I am compiling the program like this.
> 
>   ---------------------------------------------------
>     g77 "fortran file" "c file"
> 
>      Will you please suggest me the right way to call
> a C function from fortran program?
> 
>       Expecting your earliest reply.
>                 Thanking you,
>                                R.Ganesh
> 
> __________________________________________________
> Do You Yahoo!?
> Got something to say? Say it better with Yahoo! Video Mail
> http://mail.yahoo.com


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