Fortran向C传递NULL值

 

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

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

Moreover, the following two named constants are defined:

NameType 
C_NULL_PTRC_PTR
C_NULL_FUNPTRC_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

  

 

转载于:https://www.cnblogs.com/pasuka/p/4773951.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值