zoukankan      html  css  js  c++  java
  • 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
    ");
        }
        else{
            for(int i=0; i<num; i++){
                printf("Array[%d]=%d
    ", 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

      

  • 相关阅读:
    php 快速fork出指定个子进程
    批量 kill mysql 中运行时间长的sql
    socket 发送发送HTTP请求
    Qt学习笔记常用容器
    Qt学习笔记 TableWidget使用说明和增删改操作的实现
    Qt学习笔记 线程(一)
    Qt学习笔记 QMessageBox
    Qt 学习笔记 TreeWidget 增删改
    Qt Creator 常用快捷键
    Qt学习笔记 ListWidget的增删改
  • 原文地址:https://www.cnblogs.com/pasuka/p/4773951.html
Copyright © 2011-2022 走看看