Write C function that returns int to Fortran

2019-07-24 18:59发布

Ultimately I am trying to write an IPC calculator making use of Fortran to calculate and C to pass the data between the two Fortran programs. When I am done it will hopefully look like:

Fortran program to pass input -> Client written in C -> Server written in C -> Fortran program to calculate input and pass ans back

The C client/server part is done, but at the moment I am stuck trying to write a program that takes input in a Fortran program, passes it to a C program that calculates the answer. However, I see som weird behavior.

Fortran program

program calculator
    !implicit none

    ! type declaration statements
    integer x
    x = 1

    ! executable statements
    x = calc(1,1)
    print *, x

end program calculator

C function

int calc_(int *a, int *b ) {
    return *a+*b;
}

I have written a main program that verifies that int calc_() does indeed return 2 when called as calc_(1,1) in C, but when I run the program I get the output from Fortran.

I am using this makefile # Use gcc for C and gfortran for Fortran code. CC=gcc FC=gfortran

calc : calcf.o calcc.o
    $(FC) -o calc calcf.o calcc.o

calcc.o : calcc.c
    $(CC) -Wall -c calcc.c

calcf.o: calcf.f90
    $(FC) -c calcf.f90

I cannot for the world figure out why this is the case, and it's driving me mad.

1条回答
我想做一个坏孩纸
2楼-- · 2019-07-24 19:07

Almost embarrassingly simple. You must declare calc as an integer in Fortran. The working Fortran code is thus

program calculator
    !implicit none

    ! type declaration statements
    integer x, calc
    x = 1

    ! executable statements
    x = calc(1,1)
    print *, x

end program calculator
查看更多
登录 后发表回答