Previous: Accepting Fortran Strings in C Up: Passing Strings

Accepting C Strings in Fortran

The easiest way to accept C strings in a Fortran subroutine is to write the subroutine in C instead. It is possible to accept C strings by doing a two-stage bridge routine. The first stage, written in C, handles the FTN_NAME part of the transfer, and passes the string and its length as arguments to the second bridge. The second bridge, written in Fortran, accepts the strings as BYTE arrays and uses the SUBLIB routine mvlc and the passed-in length to convert them to Fortran strings, which may then be passed to the Fortran main subroutine. To get strings out, the reverse procedure is used. The Fortran bridge uses mvcl to write a BYTE array, then passes that and the length back to the C bridge, which puts a null terminator on the string and returns it to the C caller.

Examples of this type of bridge are the SPICE bridge routines, in the files ZSPBRI.COM and XSPBRI.COM. One of the bridges, for bodvar, is presented below. First is the C-callable first bridge.


void zbodvar(body, item, dim, values)

int body; char *item; int *dim; double *values; { int i; i=strlen(item);

FTN_NAME(xbodvar) (&body, item, &i, dim, values); }

This first bridge simply takes the length of the string parameter, and passes it along with the string pointer to the second-stage bridge. It also takes care of the scalar and array argument conversion, and the FTN_NAME macro. The second bridge is not intended to be called by anything except the first bridge.


      subroutine xbodvar(body, item, i, dim, values)

integer body byte item(1) integer i integer dim double precision values(*) character*80 text

text=' ' if (i.gt.80) call xvmessage('xbodvar, string too long',' ')

C Transformation to Fortran-string call mvlc(item, text, i)

call bodvar(body, text, dim, values)

return

This second bridge converts the C string (passed as a BYTE array) and the length into a Fortran CHARACTER*n variable, which is then passed into the real bodvar routine (which is the Fortran-callable version).

rgd059@ipl.jpl.nasa.gov