Skip to content

Instantly share code, notes, and snippets.

@zzj99
Last active April 9, 2016 08:07
Show Gist options
  • Save zzj99/45cbf1cffe2c1cf094e9f1492c5c127d to your computer and use it in GitHub Desktop.
Save zzj99/45cbf1cffe2c1cf094e9f1492c5c127d to your computer and use it in GitHub Desktop.
Fortran call C, deal with double**
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
/* This is a C function to be called from Fortran
* input s: the size of the array
* output x: the array of float point numbers in double precision
*/
void call_fc(double *(*x), int s)
{
double *y = malloc(s*sizeof(double));
int i;
for(i=0; i < s; i++)
{
y[i]= sin((double)i);
}
*x = y;
}
PROGRAM FORT_C
use iso_c_binding
IMPLICIT NONE
! interoperate with C
interface
subroutine call_fc(pX,s) bind(C,name='call_fc')
import
integer(c_int),value :: s ! int s
type(c_ptr) :: pX ! double **x
end subroutine
end interface
integer(c_int) :: i
integer(c_int) :: s
real(c_double), pointer :: X(:) ! double **x in Fortran
type(C_ptr) :: pX ! double **x in C
s = 10
call call_fc(pX,s)
call c_f_pointer(pX,X,(/s/)) ! convert C pointer to Fortran pointer(s)
do i=1,s
write(*,'(a4,1x,I2,1x,a2,1x,F15.8)') 'sin(', i, ') =', x(i)
end do
END program
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment