www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - string to char* in betterC

reply Abby <loniro7678 twit-mail.com> writes:
What is the proper way to get char* from string which is used in 
c functions? toStringz does returns:

/usr/include/dmd/phobos/std/array.d(965,49): Error: TypeInfo 
cannot be used with -betterC

and I think string.ptr is not safe because it's not zero 
termined. So what should I do? realloc each string with /0?

Thank you for your help
Mar 11 2020
next sibling parent reply 9il <ilyayaroshenko gmail.com> writes:
On Wednesday, 11 March 2020 at 16:07:06 UTC, Abby wrote:
 What is the proper way to get char* from string which is used 
 in c functions? toStringz does returns:

 /usr/include/dmd/phobos/std/array.d(965,49): Error: TypeInfo 
 cannot be used with -betterC

 and I think string.ptr is not safe because it's not zero 
 termined. So what should I do? realloc each string with /0?

 Thank you for your help
1. Yes. 2. A compile-time known or constants always contain trailing zero. static immutable "some text"; // contains \0 after the data.
Mar 11 2020
parent 9il <ilyayaroshenko gmail.com> writes:
On Wednesday, 11 March 2020 at 16:10:48 UTC, 9il wrote:
 On Wednesday, 11 March 2020 at 16:07:06 UTC, Abby wrote:
 What is the proper way to get char* from string which is used 
 in c functions? toStringz does returns:

 /usr/include/dmd/phobos/std/array.d(965,49): Error: TypeInfo 
 cannot be used with -betterC

 and I think string.ptr is not safe because it's not zero 
 termined. So what should I do? realloc each string with /0?

 Thank you for your help
3. You can use mir-algorithm for simplicity and speed ---- /+dub.sdl: dependency "mir-algorithm" version="~>3.7.18" +/ import mir.format; import core.stdc.stdio; void main() { printf("some_string %s", (stringBuf() << "other_string" << "\0" << getData).ptr); } ---- stringBuf() uses stack if the inner string fits into it. So, It is a mutch master than malloc/free. However, in this case C function should return pointer ownership to the caller.
Mar 11 2020
prev sibling parent rikki cattermole <rikki cattermole.co.nz> writes:
On 12/03/2020 5:07 AM, Abby wrote:
 What is the proper way to get char* from string which is used in c 
 functions? toStringz does returns:
 
 /usr/include/dmd/phobos/std/array.d(965,49): Error: TypeInfo cannot be 
 used with -betterC
 
 and I think string.ptr is not safe because it's not zero termined. So 
 what should I do? realloc each string with /0?
 
 Thank you for your help
String literals are null terminated so you can pass them straight to C. toStringz will of course not work as that relies on the GC.
Mar 11 2020