问题:
从C传递数组到Fortran,分别通过interface定义了subroutine和function的形式,前者未起作用,而后者却可以
编译器:gcc/gfortran 4.7&4.8
fortran代码:
[Fortran] 纯文本查看 复制代码 module dynamic
use,intrinsic::iso_c_binding
implicit none
interface
! Method 1: pass array via subroutine
subroutine dynamic_array(length,a,n)bind(c,name='dynamic_array')
import
implicit none
integer(c_int),intent(in),value::length
integer(c_int),intent(out)::n
type(c_ptr),intent(out)::a
end subroutine
! Mehtod 2: pass array via funciton
type(c_ptr) function dynamic_array2(length,n)bind(c,name='d_array')
import
implicit none
integer(c_int),intent(in),value::length
integer(c_int),intent(out)::n
end function
end interface
end module
program test
use dynamic
implicit none
real,pointer::array(:)
type(c_ptr)::c_array
real(c_float),allocatable::array2(:)
integer::i,j
! Initialize pointer
nullify(array)
c_array=c_null_ptr
i=10
j=0
! Method 1
! not worked
call dynamic_array(i,c_array,j)
call c_f_pointer(c_array,array,[j])
write(*,'(A)')"Pass by subroutine"
write(*,'(A,i4)')"Len of array:",j
write(*,'(A)')"Array values:"
write(*,*)array
c_array=c_null_ptr
array=>null()
i = 10
j = 0
! Method2
! worked
c_array = dynamic_array2(i,j)
call c_f_pointer(c_array,array,[j])
write(*,'(A)')"Pass by function"
write(*,'(A,i4)')"Len of array:",j
write(*,'(A)')"Array values:"
write(*,*)array
c_array=c_null_ptr
array=>null()
end program
C代码:[C] 纯文本查看 复制代码 #include <stdlib.h>
#include <stdio.h>
/* float array printing function */
void print_float_array(float *array, int len)
{
int i;
for(i=0; i<len; i++)
printf("%f | ", array[i]);
putchar('\n');
}
void dynamic_array(int n1,float *a,int *n2)
{
int i;
// allocate array
a = (float*)malloc(n1*2*sizeof(float));
// set values of array
for(i=0;i<n1*2;i++){a[i] = (float)i*i+1.0;}
//print_float_array(a,n1*2);
// set length of array
*n2 = 20;
}
float* d_array(int n1,int *n2)
{
int i;
float *a;
// allocate array
a = (float*)malloc(n1*2*sizeof(float));
// set value
for(i=0;i<n1*2;i++){a[i] = (float)i*i+1.0;}
//print_float_array(a,n1*2);
// set len of array
*n2 = 20;
return a;
}
|