Fortran向C传递NULL值

时间:2022-07-09 22:43:12

在很多C或C++的头文件定义中,NULL被指定定义为0,这里不再具体展开

gfortran的手册关于iso c binding的章节,定义NULL如下

Moreover, the following two named constants are defined:

Name Type 
C_NULL_PTR C_PTR
C_NULL_FUNPTR C_FUNPTR

Both are equivalent to the value NULL in C.

据此,从Fortran向C或C++传递空指针还是需要一些技巧,也即需要把传入参数设置为指针类型C_PTR

接下来是代码:

#include "stdio.h"

int test(int *a, int num)
{
if(!a){
printf("This is null pointer\n");
}
else{
for(int i=; i<num; i++){
printf("Array[%d]=%d\n", i+, a[i]);
}
}
return ;
}
program main
use, intrinsic:: iso_c_binding
implicit none
interface
integer(c_int) function func(array, n) bind(c, name="test")
import
implicit none
integer(c_int), intent(in), value:: n
integer(c_int), intent(in):: array(n)
end function integer(c_int) function func2(pt, n) bind(c, name="test")
import
implicit none
integer(c_int), intent(in), value:: n
type(c_ptr), value:: pt
end function
end interface type(c_ptr) :: a1
integer(c_int), target:: abc()
integer:: i abc = [, , , , ]
a1 = c_loc(abc())
! Pass array directly
i = func(abc, size(abc))
! Pass address
i = func2(c_loc(abc()), )
! Pass null pointer
i = func2(c_null_ptr, )
! Pass null function pointer
i = func2(c_null_funptr, )
end program
gfortran code_c.c code_for.f90 -o test

运行结果:

Array[1]=12
Array[2]=12
Array[3]=35
Array[4]=67
Array[5]=11
Array[1]=12
Array[2]=12
Array[3]=35
Array[4]=67
Array[5]=11
This is null pointer
This is null pointer