Fortran向C传递NULL值

在很多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

原文链接: https://www.cnblogs.com/pasuka/p/4773951.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/221367

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月13日 上午11:15
下一篇 2023年2月13日 上午11:15

相关推荐