Allocating memory in C for a Fortran allocatable

后端 未结 3 1511
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-16 06:33

We are trying to take over the memory allocation of a legacy Fortran code (+100,000 lines of code) in C++, because we are using a C library for partitioning and allocating d

3条回答
  •  无人及你
    2021-01-16 07:16

    The ISO_C_BINDING "equivalent" code:

    c++ code:

    extern "C" int size;
    extern "C" int* c_a;
    extern "C" void hello();
    int main(int args, char** argv)
    {
      size = 10; 
      c_a = new int[size];
      for(int i=0; i

    fortran code:

      MODULE MYMOD
        USE, INTRINSIC :: ISO_C_BINDING
        IMPLICIT NONE
        INTEGER, BIND(C) :: SIZE
        TYPE (C_PTR), BIND(C) :: C_A 
        INTEGER(C_INT), POINTER :: A(:)
        SAVE
      END MODULE
    
      SUBROUTINE TEST(A)
        IMPLICIT NONE
        INTEGER A(*)
        PRINT *,"A(1): ",A(1)
        PRINT *,"A(2): ",A(2)
      END 
    
      SUBROUTINE HELLO() BIND(C)
        USE, INTRINSIC :: ISO_C_BINDING
        USE MYMOD
        IMPLICIT NONE
        CALL C_F_POINTER(C_A,A,(/SIZE/))
        PRINT *,"A(1): ",A(1)
        PRINT *,"A(2): ",A(2)
        CALL TEST(A)
      END SUBROUTINE
    

    Output:

    A(1):            0
    A(2):            1
    A(1):            0
    A(2):            1
    

提交回复
热议问题