Biggest problems w/ D

BCS ao at pathlink.com
Fri Aug 10 10:06:01 PDT 2007


Reply to Gilles G.,

> Kirk McDonald Wrote:
> 
>> C. Dunn wrote:
>> 
>>> 4) Not enough help for converting between D strings and C char*.
>>> There must be conversion functions which work regardless of whether
>>> the D string is dynamic or not, and regardless of whether the C
>>> char* is null terminated.  I'm not sure what the answer is, but this
>>> has lead to a large number of runtime bugs for me as a novice.
>>> 
>> The std.string module has the toStringz and toString functions.
>> 
>> The toString function simply returns a slice over the C string:
>> 
>> char[] toString(char* ptr) {
>> return ptr[0 .. strlen(ptr)];
>> }
>> The toStringz function simply appends a null character (\0) to the
>> end of the D string:
>> 
>> char* toStringz(char[] str) {
>> return (str ~ \0).ptr;
>> }
>> These are very simple operations, and it is fairly easy to adapt them
>> to whatever needs you have.
>> 
> Well, maybe I could not find an obvious solution, but let's explain
> the problems I had with char[] and char*.
> 
> I have a DLL defining the following (extern) function:
> extern(Windows) void GetName(char* name)
> I would just like to put the name of the DLL in the variable name.
> What I would do in C is something like:
> extern(Windows) void GetName(char* name)
> {
> name = "The DLL name";
> }
> This just won't work in D... My solution for now is the following:
> extern(Windows) void GetName(char* name)
> {
> foreach(ic, c; "The DLL name\0")
> name[ic]=c;
> }
> which is ugly, but do you have a better solution?
> --Gilles
> 

if you are passing a buffer this should work

extern(Windows) GetName(char* buf) // should have length to
{
static const char[] n = "The DLL name\0";
buf[0..n.length]=n[];
}





More information about the Digitalmars-d mailing list