Passing c arrays to fortran as a variable size matrix

So, I was tasked with translating some fortran routines into C. These routines are called as part of the control flow of a large program, mainly based on C.

I translate functions one at a time, starting with the functions that are at the top of the call stack.

The problem I am facing is passing the array data from C to fortran.

Suppose we declared an array in c as

int* someCArray = (int*)malloc( 50 * 4 * sizeof(int) ); 

Now this array needs to be passed to the fortran routine to fill with data

 someFortranFunc( someCArray, someOtherParams ); 

when an array arrives at fortran land, it is declared as a variable-sized matrix:

 subroutine somefortranfunc(somecarray,someotherparams) integer somefarray(50,*) 

The problem is that fortran does not seem to correctly determine the size of the array, due to software seg-faults. When I debug a program, I find that indexing on

 somefarray(1,2) 

reports that this is an invalid index. Any references to any elements in the first column work fine, but there is only one available column in the array when it arrives at fortran.

I cannot change the fact that it is a variable size array in fortran. Can someone explain what is happening here, and is there a way to mitigate the problem from C?

[edit]

By the way, the fortran routine is called from the replaced fortran code as

 integer somedatastorage(plentybignumber) integer someindex ... call somefarray(somedatastorage(someindex)) 

where the data store is a large 1d array. No problems with oversizing the data warehouse. However, some difference between passing the C array and the fortran (sub) array causes a difference in the fortran subroutine.

Thanks!

+4
source share
2 answers

Do you think Fortran ISO C binding? I had very good results with the Fortran and C interface in both directions. My preference is not to rewrite existing, verified code. There are several types that cannot be ported with the current version of the ISO C binding, so translation may be required.

+2
source

What it should not be for others to suggest: 1. The size of the int and the size of the Integer. Because the first column has the correct values. 2. The order of rows and columns. They just get the values ​​in the wrong order if segmentation is not assigned. 3. Link to the transfer of values. Because the first column has the correct values. If the compiler does nothing behind your back.

Are you sure you are not doing this in a secret way ?:

  someCArray++ 

print the value of someCArray immediately after it is created and right before passing it. You should also print it using the fortran debugger to make sure that the compiler does not create some temporary copies to help you.

+2
source

All Articles