D2 toStringz Return Type

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Fri Nov 7 09:28:58 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)*.

We want to leave the opportunity open to not duplicate the actual memory 
underneath the string object. (Right now that opportunity is not effected.)

> 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.

C functions should have the most descriptive D signatures. "in" means 
"const" and "scope". The latter is not yet fully described at the 
moment, and may be dropped entirely. In that case, "in" remains a 
shorter synonym for "const".

> 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*);
> ======================

I think the const information should be there in the D version as well.

> 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.
> 
> 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?
> 
> 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?

I think it's better to keep it.

Andrei



More information about the Digitalmars-d mailing list