Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass an std::string to glShaderSource?

I have the following code:

glShaderSource(shader, 1, (const char **)data.c_str(), NULL); 

But it makes my program crash. How do I convert std::string into const char ** ? I also tried (const char **)& but it said "requires l-value" which I don't understand. It works fine when I use this code:

const char *data = "some code"; glShaderSource(shader, 1, &data, NULL); 

But I can't make it work directly from a std::string. I could allocate a new char array for it but that is not nice code.

I also tried with const GLchar but obviously it makes no difference.

like image 940
Rookie Avatar asked May 18 '11 15:05

Rookie


People also ask

How do I copy a std::string to a char array?

This can be done with the help of c_str() and strcpy() function of library cstring. The c_str() function is used to return a pointer to an array that contains a null terminated sequence of character representing the current value of the string.

How do I cast a std::string to char?

The c_str() and strcpy() function in C++ C++ c_str() function along with C++ String strcpy() function can be used to convert a string to char array easily. The c_str() method represents the sequence of characters in an array of string followed by a null character ('\0'). It returns a null pointer to the string.

Should I use std::string or * char?

Use std::string when you need to store a value. Use const char * when you want maximum flexibility, as almost everything can be easily converted to or from one.


1 Answers

data.c_str() returns a const char*, so do this:

const char *c_str = data.c_str(); glShaderSource(shader, 1, &c_str, NULL); 
like image 164
Dark Falcon Avatar answered Sep 23 '22 08:09

Dark Falcon