string[] to char**

simendsjo simendsjo at gmail.com
Sat Mar 24 03:38:47 PDT 2012


On Fri, 23 Mar 2012 19:23:07 +0100, Ali Çehreli <acehreli at yahoo.com> wrote:

> On 03/23/2012 08:48 AM, simendsjo wrote:
>  > What's the best way to convert char** from string[]?
>
> In C, char** communicates transfer of ownership. Is that what you are  
> trying to do? Are you going to pass a slice to a C function to be filled  
> in by that C function?
>
> Such functions usually assign to *str. In that case you can use the  
> "make slice from raw pointer" method below. I hope others will answer my  
> concern in the comment below:
>
> import std.stdio;
> import std.c.stdlib;
> import std.c.string;
>
> void C_func_with_an_out_parameter(char ** str)
> {
>      *str = cast(char*)calloc(1, 10);
>      (*str)[0] = 'A';
>      (*str)[1] = '\0';
> }
>
> void main()
> {
>      char * p;
>      C_func_with_an_out_parameter(&p);
>
>      char[] slice = p[0..strlen(p)];     // <-- make a D slice
>
>      /*
>       * Note: I don't think that the memory that
>       * std.stdlib.calloc() returns is managed by the GC. For
>       * that reason, I don't think it will be safe to share the
>       * element with another slice and expect normal behavior
>       * of element-sharing between slices.
>       *
>       * In other words, this would be risky:
>       *
>       *     char[] anotherSlice = slice;
>       */
>      writeln(slice);
>
>      free(p);
> }
>
> Ali

I'm not sure of the semantics of the function yet. Don't know if it copies  
the argument or stores it, if it frees it or expects me to free it :|
But it's not filling the array.


More information about the Digitalmars-d-learn mailing list