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

how to access common block data from c

lizhiling98
Beginner
1,386 Views

I am doing a mixed c/fortran project and has a problem for accessing fortran common block from c

uisng the intel fortran mixed language example as below.

There is a common block kwaves in fortran program, and I want to access the data x, y in c++ program, when I debug this project, in the c subroutine, I can see that the kwaves has the address, but it does not show as a struct and I can not access to its data. Anyone know why?

zhiling LI

Fortran part:


PROGRAM fmain
IMPLICIT NONE

INTERFACE
SUBROUTINE c_routine (int_arg, str_in, str_out) BIND(C)
USE,INTRINSIC :: ISO_C_BINDING ! Declares C kinds
INTEGER(C_INT), VALUE,INTENT(IN) :: int_arg
CHARACTER(KIND=C_CHAR),DIMENSION(*) :: str_in,str_out
END SUBROUTINE c_routine
END INTERFACE
real*8 x, y
!DEC$ ATTRIBUTES alias :'kwaves'::kwaves

common /kwaves/ x, y

CHARACTER(80) OUTPUT_TEXT
INTEGER IN_ARG, OUTPUT_LEN
CHARACTER(80) INPUT_TEXT


INPUT_TEXT = "Testing..."C ! C suffix adds a null terminator
IN_ARG = 123

x=1.0
CALL c_routine (in_arg, input_text, output_text)

OUTPUT_LEN = INDEX(OUTPUT_TEXT," ")
IF (OUTPUT_LEN == 0) OUTPUT_LEN = 80

WRITE (*,*) OUTPUT_TEXT(1:OUTPUT_LEN)

END


C part

#include
#pragma pack(2)

extern struct kwaves_type
{
double x, y;
}kwaves;
#pragma pack()

extern "C" void c_routine (
int int_arg,
char* input_text,
char* output_text//,
//struct kwaves_type *kwaves1
)

{
sprintf(output_text,"%s%i ",input_text,int_arg);
}

0 Kudos
1 Solution
IanH
Honored Contributor III
1,386 Views
Add extern "C" to the declaration of the struct on the C++ side.

Consider using BIND(C) to specify the external name of the common block. This should also remove any need to go a #pragma pack'ing. Consider using C_DOUBLE as the kind of the reals that are in the common block.

Note that you can interop with normal module variables too. Common blocks are an anachronism.

View solution in original post

0 Kudos
2 Replies
IanH
Honored Contributor III
1,387 Views
Add extern "C" to the declaration of the struct on the C++ side.

Consider using BIND(C) to specify the external name of the common block. This should also remove any need to go a #pragma pack'ing. Consider using C_DOUBLE as the kind of the reals that are in the common block.

Note that you can interop with normal module variables too. Common blocks are an anachronism.
0 Kudos
lizhiling98
Beginner
1,386 Views
thanks. it solve my problem.

Best wishes,
Zhiling LI
0 Kudos
Reply