string to char array?

via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Jun 3 03:28:49 PDT 2015


On Wednesday, 3 June 2015 at 10:21:20 UTC, Kyoji Klyden wrote:
> On Wednesday, 3 June 2015 at 08:11:16 UTC, Kagamin wrote:
>> On Tuesday, 2 June 2015 at 16:41:38 UTC, Kyoji Klyden wrote:
>>> src:
>>>
>>>       string source = readText("test.glvert");
>>> 	
>>> 	const string sources = source.toStringz;
>>> 	const int len = source.length;
>>> 	
>>> 	GLuint vertShader = glCreateShader( GL_VERTEX_SHADER );
>>> 	
>>> 	glShaderSource(vertShader, 1, &sources, &len);
>>
>> Judging by the docs, you don't need null-terminated strings 
>> and can use native D strings, just pass their lengths:
>>
>> 	string source = readText("test.glvert");
>>
>> 	const char* sources = source.ptr;
>> 	const GLint len = cast(GLint)source.length;
>>
>> 	GLuint vertShader = glCreateShader( GL_VERTEX_SHADER );
>>
>> 	glShaderSource(vertShader, 1, &sources, &len);
>
> Oh that also works quite well!
> Is casting necessary there though? DerelictGL treats GL types 
> as D types, and .length is size_t so wouldn't it just turn into 
> an int regardless??

size_t can be 32bit or 64bit, depending on your platform. Don't 
know how large GLint is. Assigning 64bit to 32bit requires an 
explicit cast, because it can lose information.

>
> Also the one part I don't understand is with &sources. So is 
> this passing sources as a reference, but sources itself is a 
> pointer to a pointer? I'm just a tad confused on how this part 
> works :S

A string (or any other array slice for that matter) is internally 
the equivalent of:

     struct Slice(T) {
         T* ptr;
         size_t length;
     }

(maybe the order of fields is different, I never remember that 
part)

`&source` will give you the address of that structure.


More information about the Digitalmars-d-learn mailing list