Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!uunet!interet!jim From: jim@interet.UUCP (User) Newsgroups: comp.lang.fortran Subject: Re: FORTRAN callable C functions to allocate/deallocate arrays. Summary: allocate in c, then call fortran from c Message-ID: <6@interet.UUCP> Date: 14 Nov 90 16:48:44 GMT References: <1990Nov9.210442.27086@athena.mit.edu> Organization: Interet, Maplewood, NJ Lines: 61 In article <1990Nov9.210442.27086@athena.mit.edu>, mlzerkle@athena.mit.edu (Michael L Zerkle) writes: > I am trying to develop C functions to allocate and deallocate arrays > for use in a FORTRAN progam that would run on a number of different > UNIX boxes (DEC VS3100, Apollo, SGI 4D/210, etc.). > > program testgetm > real*8 a(1) > > call getmd(a,maxa) This call overwrites the address of a, which I believe is incorrect, although it may work on certain platforms. The "a" address is a constant within the meaning of Fortran. > void getmd_(double *array, int *nelem) It is dangerous to declare nelem an int pointer. It is far better to de- clare it a long pointer, since all fortrans I know treat most variables as four bytes, or long. This even applies to logical. We allocate storage for Fortran programs as follows: subroutine dostuf(a,maxa) integer maxa double precision a(maxa) .... massive great things happen .... end The real work is done in dostuf, and Fortran expects a pointer "a" which you provide by calling it from c. void ccall_(nelem) /* used to call dostuf_() with needed storage */ long *nelem; /* size of array needed */ { double *array; /* just an example, not tested */ array = (double *) calloc((size_t) *nelem, (size_t) sizeof(double)); dostuf_(array, nelem); free((void *) array); } You must call ccall() from Fortran after Fortran figures out how big the array needs to be: program myprog ... c we need isize elements. call ccall(isize) c large job returns. ... end The above is highly portable, except that you have the portability problem of linking c and Fortran in the first place. Your solution is more gen- eral and powerful, but I would be concerned with the portability. I hope this helps. In our shop, we solve the problem of linking Fortran with c first, and we will not use hardware for which this is not easy. Then we solve all other portability problems by writing in either c or Fortran as appropriate. Storage allocation is portable in c, so c is used in the above example. Note that f2c solves the problem of linking Fortran with c. Jim uunet!interet!jim