Alain
Alain

Reputation: 572

Fortran90 and size of arrays created in C++

I'm trying to call some Fortran 90 code from a C++ main program. The Fortran subroutine takes a array of double (call it X) as parameter, then proceeds to use size(X) in many places in the code. I call the routine with a C array created through

double *x = new double[21]

but when I print the result of size(X) in the Fortran code I get 837511505, or some other big numbers.

Right now I can modify the fortran code, so worst case is to rewrite the function, passing the size as a parameter. But I'd rather not do it.

Does anyone know if there's a way I can create the C array in such a way that the Fortran routine can figure out its size?

Upvotes: 2

Views: 247

Answers (3)

David Folkner
David Folkner

Reputation: 1199

I personally use a ton of mixed coding from c++ to fortran 90/95/2003. I typically use gfortran as my compiler, but to avoid this issue, it is common practice to always send the size of the arrays. This even allows you to change the shape. Consider a 2 dimensional array containing x,y points:

double* x = new double[2*21]

real(8),intent(in),dimension(2,21)::x

This is a very handy feature and will then allow you to use the size command. The answers about compiler specifics are correct. To make your code usable on most compilers you should specify length when using multi-language interfaces.

Upvotes: 0

vmsnomad
vmsnomad

Reputation: 339

Intel F95 uses array descriptor structure, which apart from the array pointer also store the bounds and dimension information. size() gets the information from the descriptor.

Since you're passing from C only pointer, no descriptor info is available, thus size() returns gibberish.

Generally, you're in the rough territory of mixed language programming, where arrays and structures are often a programmer's pain. Intel compiler user doc has a separate section about C<=>F95 mixed calling.

In particular, check about interfaces and binding -- a nice F95 feature that helps in inter-language calls.

The good news, C<=>F95 calling works very well once you stick to the conventions.

Upvotes: 0

wallyk
wallyk

Reputation: 57774

This is an implementation-specific feature. Many implementations (RSX and OpenVMS, for example) define a structure for passing a pointer to the data as well as a description of the dimensions, types, etc. Other implementations pass no such thing unless the external declaration explicitly invokes a mechanism to generate a descriptor. Most others provide no such mechanism.

Without knowing which implementation in use:

a) read the compiler's documentation
b) have the compiler generate assembly, and inspect it to see what it expects

Upvotes: 1

Related Questions