D processing a char* allocated by a C module
Jarrett Billingsley
kb3ctd2 at yahoo.com
Wed Jun 20 13:46:31 PDT 2007
"Carlos Smith" <carlos-smith at sympatico.ca> wrote in message
news:f5bvrr$2ui6$1 at digitalmars.com...
> Hi !
>
> I have a C module, compiled with DMC.
> Coming from this C module:
>
> extern (C)
> {
> int ccleng; // strlen(cctext)
> int pos;
> char *cctext; // point into an input buffer
> int yylex();
> }
>
> cctext is a pointer to a buffer allocated by yylex().
> the buffer is small and can be freed or overwritten
> by yylex();
>
> In the D module, i do:
>
> char[] dtext = toString(cclex);
>
> and dtext get corrupted (not always).
>
> I guess toString do not make a new copy of cctext,
> just point to it.
>
> How can i duplicate cctext, in D ? (strdup does not exist ?)
> Will the D copy be garbage collected ?
Slice and dup!
char[] dtext = cctext[0 .. ccleng].dup;
You can slice pointers to turn them into D arrays, and then you can .dup
them to copy the array into a new array. This duplicated array will not be
overwritten by yylex() and will be garbage collected.
More information about the Digitalmars-d-learn
mailing list