(j3.2006) Should character strings be interoperable with char arrays?

Aleksandar Donev donev1
Mon Jul 23 21:29:35 EDT 2007


This is a (random) rant about C Interop based on some codes I was writing 
today...just to illustrate the pains of C Interop for strings (which are not 
interoperable with char arrays unless LEN=1) and C_LOC. 

This is a procedure that writes several variables defined a mesh to a database 
file to be read by a visualization software. It takes an array of strings and 
an array of arrays (C pointers), one per variable:

void write_point_mesh(const char *filename, int ub, int npts, float *pts,
                      int nvars, int *vardim, const char * const *varnames,
                      float **vars)

Fortran interface:

      SUBROUTINE write_point_mesh(filename, ub, npts, pts, nvars, &
   vardim, varnames, vars) BIND(C)
         CHARACTER(C_CHAR), DIMENSION(*), INTENT(IN) :: filename
         INTEGER(C_INT), VALUE :: ub, npts, nvars
         REAL(C_FLOAT), DIMENSION(3*npts) :: pts 
         INTEGER(C_INT), DIMENSION(nvars) :: vardim  
         TYPE(C_PTR), DIMENSION(nvars) :: varnames 
         TYPE(C_PTR), DIMENSION(nvars) :: vars

Usage in an actual code requires using CHARACTER arrays instead of strings, 
and adding TARGET to all the arrays:

 v_string(2)=(/"v",C_NULL_CHAR/), &

CALL write_point_mesh(... varnames=(/C_LOC(v_string), C_LOC(rho_string)/), &
 vars=(/C_LOC(velocities), C_LOC(densities)/))

The only way to use the hack we provided to allow strings to be passed as 
actuals corresponding to char arrays is to write wrappers.

It should be easier than this!

Aleksandar Donev, Ph.D.
Lawrence Postdoctoral Fellow @ LLNL
High Performance Computational Materials Science and Chemistry
E-mail: donev1 at llnl.gov
Phone: (925) 424-6816  Fax: (925) 423-0785
Address: P.O.Box 808, L-367, Livermore, CA 94551-9900
Web: http://cherrypit.princeton.edu/donev

More information about the J3 mailing list