Passing strings between C and Fortran routines is not encouraged. However, a Fortran character-string-valued function is equivalent to a C function with two additional first arguments--data address and string length. The general pattern for the Fortran function and its corresponding C function is:
Fortran function |
C function |
---|---|
CHARACTER*n FUNCTION C(a1, ..., an) |
void c_ (result, length, a1, ..., an) char result[ ]; long length; |
Here is an example:
Table 11-15 A Function Returning a CHARACTER String
Fortran calls C |
C calls Fortran |
---|---|
CHARACTER STRING*16, CSTR*9 STRING = ' ' STRING = '123' // CSTR('*',9) ... ------------------------------ void cstr_( char *p2rslt, int rslt_len, char *p2arg, int *p2n, int arg_len ) { /* return n copies of arg */ int count, i; char *cp; count = *p2n; cp = p2rslt; for (i=0; i<count; i++) { *cp++ = *p2arg ; } } |
void fstr_( char *, int, char *, int *, int ); char sbf[9] = "123456789"; char *p2rslt = sbf; int rslt_len = sizeof(sbf); char ch = '*'; int n = 4; int ch_len = sizeof(ch); /* make n copies of ch in sbf */ fstr_( p2rslt, rslt_len, &ch, &n, ch_len ); ... ------------------------------ FUNCTION FSTR( C, N) CHARACTER FSTR*(*), C FSTR = '' DO I = 1,N FSTR(I:I) = C END DO FSTR(N+1:N+1) = CHAR(0) END |
In this example, the C function and calling C routine must accommodate two initial extra arguments (a pointer to the result string and the length of the string) and one additional argument at the end of the list (length of character argument). Note that in the Fortran routine called from C, it is necessary to explicitly add a final null character.