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

C calling fortran with character arguments

rsm2
초급자
759 조회수

When calling a Fortran subroutine that has a character argument from C code should the hidden length argument be passed as an int or size_t?

The reason I ask is because I'm having the problem below and I'm not sure if it my code that is at fault or not.

In my C code I have these functions declared

void f_code5_ (char*,int*,int*,int*,int*,int*,int);
void f_code5s_(char*,int*,int*,int*,int*,int*,size_t);

and call them

char * text=0;
text = malloc(20);
strcpy(text,"123x123");
int i1,i2,i3,i4,i5,i6;

f_code5_(text,&i1,&i2,&i3,&i4,&i5,strlen(text));
f_code5s_(text,&i1,&i2,&i3,&i4,&i5,strlen(text));

The f_code5 (f_code5s is the same) is

subroutine f_code5(desc,i1,i2,i3,i4,i5)
implicit none
character*(*) desc
integer i1,i2,i3,i4,i5
character t*255
t = desc
print*,'t5='//desc
return
end

The code aborts (SEGV) on the print statement and if I look at the variable 't' it has the7 characters from desc plus garbage characters to fill it out rather than spaces. The idb debugger shows the hidden argument to have a value of 7 (which is correct) but the command 'whatis desc' returns character*140733193388039 (which is 0x7ffff00000007)

If I call f_code5s immediately before f_code5 then it works. It also works if I remove one of the integer arguments. If I use t=desc(1:len(desc)) then 't' has the correct value.

I am using ifort 10.1.023 for the fortran code and gcc for the C code.

0 포인트
1 솔루션
Steven_L_Intel1
759 조회수
The size is expected as size_t.

원본 게시물의 솔루션 보기

0 포인트
5 응답
Steven_L_Intel1
760 조회수
The size is expected as size_t.
0 포인트
TimP
명예로운 기여자 III
759 조회수
I have run into customers who say that any OS (such as 64-bit linux and Windows and, I suppose, MacOS) where size_t is not the same as int is broken. However, there is a reason why standard C and Fortran ISO_C_BINDING distinguish them. Observing the standard would remove 1 more reason for having to "port" from 32- to 64-bit.
0 포인트
rsm2
초급자
759 조회수

Thanks for those answers.

I am still curious as to why

t=desc treats the length as a huge number but

t=desc(1:len(desc)) has the correct length of 7

it suggests to me that the len() function is only pulling 4 bytes off the stack.

I would expect these statements to be equivalent.

0 포인트
Steven_L_Intel1
759 조회수
I recall a compiler bug, fixed long ago, that could account for this discrepancy. Please try it with a current compiler.
0 포인트
rsm2
초급자
759 조회수
Thanks again.
0 포인트
응답