Maurice Lombardi wrote:
Frank Heckenbach wrote:
Oldham, Adam wrote:
The problem is in using String2CString -- it allocates storage for the CString on the stack which becomes invalid after the return from the function. (I'd be willing to admit that this probably isn't documented anywhere, though ...)
You might want to use NewCString instead which allocate storage from the heap. Of course, you'll have to Dispose it sometime later to avoid memory leaks.
So the problem is with a misnaming of CString. CString is a pointer to a CString (array of char) rather than the array itself. (in the doc it is said ^Char in C style). Probably a name like pCString (like BP's pChar but more exact) would avoid any confusion of this kind in being clear by itself. Clarity is one of the benefits one looks in using pascal rather than C.
(I also think `PChar' is unprecise because is suggests that it's a pointer to a single char rather than a string -- which is the same in C, but not in Pascal.)
Strings in C are pointers (to 0-terminated char arrays) by definition. The typical Pascal programmer may not know this, but the typical Pascal programmer should not need to use CStrings, anyway. Those who use them, I think, can be expected to know what they really mean.
In general, I think, when dealing with low-level stuff, it's better to have a basic understanding of the issues, i.e. it's easier to understand the problems if you know what strings in C look like than if you blindly follow some rules that cover many, but not all situations, like: you may pass Pascal strings to CString parameters, but not vice versa, etc. -- As long as it's transparent to the caller, such rules of thumb will work (e.g., in the GPC unit, there are some routines with CString parameters, but the caller doesn't notice because they're read only and passing Pascal strings works just like expected), but when one is using CStrings in one's own code, I think one better knows what they are. (I'm not saying that Adam doesn't know what he's doing -- as I said, the difference between String2CString and NewCString may not be documented anywhere yet ...)
There are some more pitfalls about CStrings, and we can't avoid them all by renaming, so I think the effort is not worth the possible benefit (it would require changes in many places in GPC and 3rd party code).
Frank