3

I'm using a function from SDL, and one of the parameters is of type const GLchar* const*, so in order to call it, I would need to pass in a reference of a C-string like this:

const char *str = "test";
glShaderSource(... , &str, ...);

However, I have an std::string that I want to pass in, and doing something like this gives an error:

std::string str = "test";
glShaderSource(... , &str.c_str(), ...);

I know that I can simply make a new const char* variable and save the std::string to it like this:

const char *cstr = str.c_str();

But is there any way around this? I don't like having to make a new variable. I tried using a lambda but that didn't work.

Archie Gertsman
  • 1,601
  • 2
  • 17
  • 45

2 Answers2

6

No, there's no way around it.

The function glShaderSource needs a pointer to a pointer to a character buffer (because it wants you to pass one or more C-strings), and you can't take the address of an rvalue (which is what the expression str.c_str() is).

But that's not really a problem, since in your final example all you're doing is assigning a pointer to a pointer. This is extremely cheap and easy.

Don't be afraid of "making a new variable" — naming things is good anyway.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
0

I think the question is: why does the function need a pointer-to-a-pointer? In a lot of cases with c-style functions, they provide this kind of interface because they want to modify the target pointer to point to something else (such as something created internally by the function). If that is the case, then assigning the result of string::c_str() to a variable and then passing it in is kind of pointless, as it would be re-assigned to point to something else anyway.

I recommend you check the documentation of this function more thoroughly to ensure this is not the case (which it probably is).

Smeeheey
  • 9,906
  • 23
  • 39