Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.

Passing array of derived type to C

David_T_5
Beginner
711 Views

I have a Fortran derived type with dynamically allocated memory.

TYPE :: A

REAL, DIMENSION(:), POINTER :: array_of_reals

END TYPE A

To pass this derived type to C, I have a C struct

struct A_struct {

double* array_of_reals

}

When I pass the Fortran type to C, I convert the Fortran pointer to C pointer using

C_LOC(array_of_reals)

This works fine.

Now, if I have an array of TYPE A,

TYPE A_Array

TYPE(A), DIMENSION(:), ALLOCATABLE :: array_of_A

END TYPE A_Array

 

I cannot simply pass C_LOC(array_of_A) to C because the memory pointer allocated in each element of array_of_A is not compatible with C.  Is this correct?  If so, how can I pass an array of derived type that contain dynamically allocated memory?

It seems I need to pass an array of C pointers 

TYPE(C_PTR), DIMENSION(:), ALLOCATABLE :: array_of_A

but this won't work because I cannot use dynamic arrays with BIND(C).

 

 

 

 

 

 

 

 

0 Kudos
2 Replies
Steven_L_Intel1
Employee
711 Views

You can't use a derived type that contains a POINTER or ALLOCATABLE. You CAN use an allocatable or pointer deferred-shape array as a dummy argument in the 2016 version, but Fortran will pass it as a "C descriptor" (a feature from Fortran 2015) and the C code will need to include ISO_Fortran_binding.h and use the declarations in it to access the descriptor.

You can have a derived type with a C_PTR component and pass that to C.

0 Kudos
FortranFan
Honored Contributor II
711 Views

@David,

See this thread:

https://software.intel.com/en-us/forums/intel-visual-fortran-compiler-for-windows/topic/593294

If, by any size, the memory allocation and deallocation of pointer components in the struct is handled on the C side (for example, this may be a natural occurrence when the executive is on the C side and the Fortran code is more like library invocations and say the problem (array) size(s) is sent back to C from a separate Fortran call or from user input), then look at messages #11 and #12 in the above thread which describe how such C structs can interoperate with Fortran.

0 Kudos
Reply