string[] to char**
Ali Çehreli
acehreli at yahoo.com
Fri Mar 23 11:23:07 PDT 2012
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
More information about the Digitalmars-d-learn
mailing list