Alex Rivera | Logout

How to pass an std::string to glShaderSource?

Asked 2011-05-18T15:52:58.730
39

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.

Edit
Report

1 Answer

13

You can get a reasonable-looking call by using a helper class. Define this class:

struct StringHelper {
  const char *p;
  StringHelper(const std::string& s) : p(s.c_str()) {}
  operator const char**() { return &p; }
};

Then, when you need to call glShaderSource, do it this way:

glShaderSource(shader, 1, StringHelper(data), NULL);
answered 2011-05-18T16:40:06.817

Your Answer