ability to support strtol() from foreign
"Hoehle, Joerg-Cyril" <[email protected]> Wed, 27 Mar 2002 14:33:25 +0100
| Newsgroups | gmane.lisp.uffi.general |
|---|---|
| Message-ID | <[email protected]> |
Hi, Kevin Roserberg wrote: > Right now, to support the strtol routine > (examples/strtol.cl), I need to do pointer arithmetic to > properly handle the output of the C function. It's funny that you mention strtol(), since I also covered it in my draft article about FFI design. (I sent you the draft). I feel it's a function that's worth *not* supporting. Which doesn't mean that the problem of pointer into inner structures (or amid strings) disappears. Here's what I felt I had to say on strtol in my article: " long strtol(const char* text, char **rest); [...] Returning Pointers into strings - don't! [...] o The culprit is the C idiom of returning a pointer into a part of a data structure, i.e. the rest string: C people favour pointer arithmetic instead of using indices on arrays like people from many other languages do. o Knowing this, if our goal is to design a library purported to be usable from other languages as well, we better avoid returning such pointers. o What we can do for know in order to stay sane is to either add a wrapper function in C around strtol which would return an index as an integer (*rest-text), or to write this wrapper in Lisp. [...] Let's have a closer look at what happens when using the initial function definition for strtol in CLISP with a call like (strtol "123 bla...bla"). There is no means to declare that the rest pointer being returned is a pointer into the original string. Therefore it will allocate a new string in Lisp to contain the rest. This is extremely wasteful! We don't want that. First, notice that this is not a problem with Lisp, but with the attempt of foreign language integration. More specifically, it shows up as a problem when trying to call functions that embed C idioms from any other language with radically different idioms. I once had exactly the same problem when calling from within the REXX language a function host (a regexp package) written in C. In our case, using PARSE-INTEGER and its :start keyword instead of strtol would lead to a native Lisp solution as efficient as possible. Here's how to write a wrapper for strtol in CMUCL: [...] You'll notice that CMUCL still has powerful primitives that will let you do away with manual memory management. "-end partial quotation BTW, feel free to upload my draft article to sourceforge UFFI documentation/ if you wish. Regards, Jorg Hohle.