How do I call a C routine inside a Fortran program?
Note: For information about calling a Fortran routine inside a C program, see How do I call a Fortran routine inside a C program?
Before calling a C routine from inside a Fortran program, make sure any calls between the languages are compatible. For example, C stores arrays in row major while Fortran does it in column major. Therefore, when you call a Fortran subroutine in C, you need to transform the matrix before making the call.
Assuming your calls are valid, use this sample code as an example:
username@BigRed:~/call_c_from_f> cat fortran_driver.f PROGRAM fortran_driver IMPLICIT NONE REAL :: one_point_x, one_point_y, another_point_x, another_point_y EXTERNAL calc_dist one_point_x = 20.0 one_point_y = -10.0 another_point_x = 7.0 another_point_y = 14.0 CALL calc_dist(one_point_x, one_point_y, another_point_x, another_point_y\) END PROGRAM fortran_driver username@BigRed:~/call_c_from_f> cat c_worker.c #include <math.h> void calc_dist(float *a_x, float *a_y, float *b_x, float *b_y\) { float x_part, y_part, distance; x_part = (*b_x - *a_x\) * (*b_x - *a_x\); y_part = (*b_y - *a_y\) * (*b_y - *a_y\); distance = sqrt(x_part + y_part\); printf("The distance between the embedded points is %12.4e\n", distance\); } username@BigRed:~/call_c_from_f> cat compile.script xlc -c c_worker.c xlf90 -o find_dist fortran_driver.f c_worker.o username@BigRed:~/call_c_from_f> ./compile.script ** fortran_driver === End of Compilation 1 === 1501-510 Compilation successful for file fortran_driver.f. username@BigRed:~/call_c_from_f> ./find_dist The distance between the embedded points is 2.7295e+01This document was developed with support from the National Science Foundation (NSF) under Grant No. 0503697 to the University of Chicago and subcontracted to Indiana University. Additional support was provided by IU through its participation in the TeraGrid, which is supported by the NSF under Grants No. 0833618, SCI451237, SCI535258, and SCI504075. Any opinions, findings, and conclusions or recommendations expressed in this material are those of the author(s) and do not necessarily reflect the views of the NSF.
Last modified on April 07, 2008.






