Prev: How to measure the net time spent in a program?
Next: Correct way to write a wrapper for C functions that accept/returnstrings
From: glen herrmannsfeldt on 9 Mar 2010 14:39 In comp.lang.fortran Eli Osherovich <eli.osherovich(a)gmail.com> wrote: > On Mar 9, 7:58?pm, glen herrmannsfeldt <g...(a)ugcs.caltech.edu> wrote: >> In comp.lang.fortran Eli Osherovich <eli.osherov...(a)gmail.com> wrote: >> > On Mar 9, 3:18?pm, Malcolm McLean <malcolm.mcle...(a)btinternet.com> (snip) >> >> Returning strings you have to make a judgement call. Sometimes it is >> >> easier for caller to pass you a char * to a buffer which he controls, >> >> sometimes it is easier to return a char * containing allocated data. >> >> (Just rarely you want to retrn a char * to a static buffer). The fisrt >> >> method is likely to be faster and doesn't depend on malloc(), the >> >> second method is much less likely to allow a buffer overflow, and may >> >> the the only practical method if the length of the return string can't >> >> be predicted in advance. >> The first and third are most commonly used by C library routines, >> and by user written functions. ?C programmers hate to have to keep >> track of memory malloc()ed by other routines. (snip) >> > May be I do not understand you correctly... but my impression is you >> > are talking about C not Fortran. >> Well, you have to talk about C somewhere. ?As a C wrapper to a Fortran >> function, you have to do what other C programs can use. ?As a wrapper >> to a C funtion, you have to live with what the C function does. >> The above three are pretty much the choices you have. > I want a Fortran wrapper for C functions whose prototypes were given > in the first message. Where does the (char*) return value come from? Presumably one of the sources indicated above. The right answer is that they are of TYPE(C_PTR), but often that isn't what you want. You can, for example, pass an array of CHARACTER(C_CHAR) to a C routine expecting a (char *) if you don't put VALUE on the interface. You can't really do that for the return value, though. If the C routine returns a pointer to static storage (usually of known size), then the Fortran routine can return CHARACTER*(size), which you copy from the returned C value. If the C routine returns malloc()ed space, ALLOCATE an appropriate sized CHARACTER variable, copy the value, free() the pointer, and return. (That is, if functions can return ALLOCATABLE CHARACTER variables.) If the function returns a pointer into the input string, you might return an integer offset. For example, the C library routine strstr(), sometimes known as index(), returns a pointer into the argument string. You can't really do that in Fortran, but returning the difference between the two pointers makes sense. (strstr() can also return NULL, which you have to consider separately.) Unfortunately, subtracting TYPE(C_PTR) in Fortran isn't easy. -- glen |