Passing string literals to C

John Colvin via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Dec 31 04:25:44 PST 2014


On Wednesday, 31 December 2014 at 11:45:33 UTC, Mike Parker wrote:
> On 12/31/2014 8:19 PM, Laeeth Isharc wrote:
>> Argh - no way to edit.
>>
>> What's best practice here?
>>
>> D strings are not null-terminated.
>> ===
>> cpling.c
>>
>> char* cpling(char *s)
>> {
>>   s[0]='!';
>>   return s;
>> }
>> ===
>> dcaller.d
>>
>> extern(C) char* cpling(char* s);
>>
>> void callC()
>> {
>>   writefln("%s",fromStringz(cpling("hello\0")));
>> }
>>
>> or
>>
>> void callC()
>> {
>>   writefln("%s",fromStringz(cpling(toStringz("hello"))));
>> }
>>
>> ===
>>
>> am I missing a better way to do this?
>
> String literals are always null-terminated. You can typically 
> pass them as-is and D will do the right thing (you can also 
> pass "MyStr".ptr if you want).

String literals can implicitly convert to const(char)* or 
immutable(char)*. Neat. It doesn't appear to apply to array 
literals in general though...


More information about the Digitalmars-d-learn mailing list