0

我正在尝试将用 C 初始化的 4D 数组传递给 FORTRAN 函数。按照上一个问题的建议,我首先将数据数组分配为具有单个 malloc 的连续数据,然后分配指向指针的指针,使它们最终指向数据数组内部。此方法适用于 3D 数组。但是,当我转到 4D 数组时,我没有得到 FORTRAN 中预期的值。当我 malloc 为 C 数组 > 3 维的内存分配内存时,是否需要更改某些内容,或者 alloc_4D_double 函数中是否存在错误?

代码摘录:

#include <stdio.h>
#include <stdlib.h>

double f_function(double ****);

double ****alloc_4D_double(int wlen, int xlen, int ylen, int zlen, double *ary)
{
    int i,j,k;

    double ****multiDary = (double****)malloc(wlen*sizeof(double***));

    for (i = 0; i < wlen; i++) 
    {
        multiDary[i] = (double***)malloc(xlen*sizeof(double**));

        for (j = 0; j < xlen; j++) 
        {
            multiDary[i][j] = (double**)malloc(ylen*sizeof(double*));

            for (k = 0; k < ylen; k++) 
            {
                multiDary[i][j][k] = (double*)malloc(zlen*sizeof(double));
            }
        }
    }

    for (i = 0; i < wlen; i++) 
    {                     
        for (j = 0; j < xlen; j++) 
        {
            for (k = 0; k < ylen; k++) 
            {
                multiDary[i][j][k] = &ary[zlen*(k + ylen*(j + xlen*i))];            
            }
        }
    }

    return multiDary;
}

int main ( void ) {

    // create contiguous memory
    double *data1D = (double*)malloc(2 * 4 * 10 * 10 * sizeof(double));

    // map memory locations to allow use of array syntax
    double ****exposure4D = alloc_4D_double(2, 4, 10, 10, exposure1D);

    // assign a value
    data[0][1][4][4] = 0.777;

    // pass the pointer to FORTRAN
    f_funtion(data1D)

    return 0;
}

integer(4) function f_function(data)  BIND(C)
    use, intrinsic :: iso_c_binding    

    implicit none        
!
    real(C_DOUBLE)       , intent(in),      dimension(2,4,10,10) :: data

    // this value does not evaluate to 0.7777
    write(*,*), data(1,2,5,5) 

    // this value does evaluate to 0.7777
    write(*,*), data(1,1,9,2) 

end function f_function 
4

0 回答 0