Fortran and C inter-function call with interger as parameter

Please look at these two small functions. I passed an long interger into the C function and changed its value and passed back into fortran. but the value is not correct. If I didn’t use the long interger, the value is correct. Why?
Fortran code:

program foo
external boo

integer8 a
a = -10
call boo(a)
print
, a
end program foo

C code:

#include <stdio.h>

void boo_(long int* a)
{
printf(“PASSIN VALUE: %d\n”, *a);
*a= 100;
printf(“Within boo subroutine a = %d\n”, *a);
return;
}

You can try to run these two code and if you chang the long int and integer*8 as int and integer respectively, you will see the a value after boo function all is changed to 100 but this long int simply doesn’t work.

Thank you.

Hi Warren,


Are you compiling on a 32-bit system? In 32-bits, a ‘long int’ has a size of 4 bytes while in 64-bits it has a size of 8 bytes. A ‘long long int’ is 8 bytes in both 32 and 64-bits so might work better here.

% cat tmp_c.c
#include <stdio.h>

void boo_(long int* a)
{
  int size;

  size = sizeof(long int);

  printf("PASSIN VALUE: %d,  Size of a long int: %d\n", *a, size);
  *a= 100;
  printf("Within boo subroutine a = %d\n", *a);
  return;
}
% cat tmp_f.f
      program foo
      external boo

      integer*8 a
      a = -10
      call boo(a)
      print*, a
      end program foo

%pgf90 tmp_f.f tmp_c.c -tp k8-64
tmp_f.f:
tmp_c.c:
% a.out
PASSIN VALUE: -10,  Size of a long int: 8
Within boo subroutine a = 100
                      100
% pgf90 tmp_f.f tmp_c.c -tp k8-32
tmp_f.f:
tmp_c.c:
% a.out
PASSIN VALUE: -10,  Size of a long int: 4
Within boo subroutine a = 100
              -4294967196
  • Mat

thank you, the problem solved. Nice job.