D2 toStringz Return Type

Sean Kelly sean at invisibleduck.org
Fri Nov 7 09:29:34 PST 2008


Mike Parker wrote:
> I'm curious as to why toStringz in D2 returns const(char)* instead of 
> just a plain char*. Considering that the primary use case foe the 
> function is interfacing with C code, it seems rather pointless to return 
> a const(char)*.
> 
> Consider the D2 versions of the function declarations in the std.c 
> package. The 'const char *' declarations from C are replaced with 'in 
> char*' from D. To what end? The C side doesn't know and doesn't care 
> about const declarations in D. You could add any sort of modifier you 
> want on the D side and it would serve no real purpose.

It affects what values may be passed as parameters to these routines. 
String literals, for example, may only be passed as const or invariant 
parameters in D2.

> Then consider all of the existing (and future) bindings to C libraries 
> out there. The vast majority have this sort of function prototype:
> 
> =====================
> // from the C header
> void someFunc(const char*);
> 
> // in D
> extern(C) void someFunc(char*);
> ======================
> 
> This works with D1, but anyone using this library with D2 will either 
> have to change such prototypes to include the 'in' modifier, or cast 
> every call to toStringz.

Yup.  I wish someone had said to use "in" for this from the outset.  But 
conversion isn't too terrible in most cases.  I converted all of Tango's 
C and Posix headers in an afternoon.

> I'm updating Derelict now to work with D2 and found this to be 
> incredibly annoying. But before I go through every API Derelict binds to 
>  in order to figure out which char* parameters should get the 'in' 
> modifier, I thought I'd ask here if there is any real purpose in 
> requiring this sort of thing?

Passing const variables.

> Is there any major use case for toStringz other than passing 
> null-terminated strings to C functions? If not, then having a 
> const(char)* return type is really superfluous. It doesn't do anything! 
> Can we just remove the const?

See above :-)


Sean



More information about the Digitalmars-d mailing list