Fortran/C Mixing : How to access dynamically allocated C array in Fortran?

百般思念 提交于 2019-12-12 04:59:03

问题


I'm currently experiencing an memory issue: I have a main program coded in Fortran which calls a C/C++ subroutine to perform some tasks and store data in a dynamically allocated array. The thing is I need to have access to these data when back to the Fortran main program. I tried to declare a C pointer (TYPE(C_PTR)) in fortran to point to the array but it doesn't seem to work. The array is present within the C subroutine but I get a segfault when trying to access it when I'm back to the main Fortran program. I give my code here, any ideas? Thank you for helping !!

Fortran:

PROGRAM FORT_C
use iso_c_binding
IMPLICIT NONE

    interface
        subroutine call_fc(pX,s) bind(C,name='call_fc_')
            import
            integer(c_int)              :: s
            type(c_ptr), pointer        :: pX
        end subroutine
    end interface

    integer(c_int)                              :: i
    integer(c_int)                              :: s
    integer(c_int), pointer                     :: X(:)
    type(C_ptr), pointer                        :: pX

    s=100

    call call_fc(pX,s)
    call c_f_pointer(pX,X,(/s/))

    ! This here provocates a segfault
    do i=1,s
        write(*,*), i
        write(*,*) X(i)
    end do

END

C subroutine:

#include <iostream>
#include <cstdlib>

using namespace std;

extern "C" 
{
    void call_fc_(int **x, int *s);
    void c_func_deallocate(int **x);
}


void call_fc_(int **x, int *s)
{
    int *y = (int *) malloc(sizeof(int)*(*s));
    for(int i=0; i < *s+10; i++)
    {
        cout << i << endl;
        y[i]=i;
    }
    *x = y;
}

void c_func_deallocate(int **x)
{
    free(*x);
}

Outpout:

           1
forrtl: severe (174): SIGSEGV, segmentation fault occurred
Image              PC                Routine            Line        Source             
exemple            0000000000402E1F  Unknown               Unknown  Unknown
exemple            0000000000402C8C  Unknown               Unknown  Unknown
libc.so.6          000000331241ECDD  Unknown               Unknown  Unknown
exemple            0000000000402B89  Unknown               Unknown  Unknown

来源:https://stackoverflow.com/questions/23518641/fortran-c-mixing-how-to-access-dynamically-allocated-c-array-in-fortran

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!