标签:
在很多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=0; i<num; i++){ printf("Array[%d]=%d\n", i+1, a[i]); } } return 0; }
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(5) integer:: i abc = [12, 12, 35, 67, 11] a1 = c_loc(abc(1)) ! Pass array directly i = func(abc, size(abc)) ! Pass address i = func2(c_loc(abc(1)), 5) ! Pass null pointer i = func2(c_null_ptr, 5) ! Pass null function pointer i = func2(c_null_funptr, 5) 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
标签:
原文地址:http://www.cnblogs.com/pasuka/p/4773951.html