Quantcast
Channel: Intel® Fortran Compiler
Viewing all articles
Browse latest Browse all 3270

C interoperability: trivial question

$
0
0

This is similar to the topic discussed here:

https://software.intel.com/en-us/forums/topic/387235

This should be a trivial question for you guys, but it's nagging me anyways...

Please take a look at the very simple pair of Fortran/C code below. 

#include <stdio.h>
#include <math.h>

void sub_f1( float f1, float *f2 )
{
   float f3;
   f3= sin(f1);
//    f2= &f3;
   *f2= f3;
}
program tes_sub_f1
use, intrinsic :: iso_c_binding
implicit none
interface
   subroutine sub_f1(f1, f2) bind(c)
   import :: c_float
   real(c_float), value :: f1
   real(c_float), intent(out) :: f2
   end subroutine sub_f1
end interface
real(c_float) :: ff1, ff2
!
do
   write(*, '(/,a)', advance= 'no')'Enter f1: '
   read(*,*)ff1
   print*, 'F: sin(f1)=', sin(ff1)
   call sub_f1(ff1, ff2)
   print*, 'C: sin(f1)=', ff2
end do
end program tes_sub_f1

I'm trying to understand how to pass values to a C subroutine (void function) and receive results in other variables. 

The program works all right.  I enter any real number, fortran passes the value to the sub_f1 C routine, it evaluates the sin of the number and returns the result to Fortran which displays the correct value.

However, if I uncomment the line

f2= &f3;

i. e., the pointer f2 first points to the address of f3, and after to its value, it will always return 0 to fortran.

Is this behavior expected?

Also: if I want to pass results (scalars, arrays) FROM C to Fortran, the said results must always be passed as pointers? I all the tests I did, this was the only possibility that worked.

Thanks.


Viewing all articles
Browse latest Browse all 3270

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>