简体   繁体   中英

Output const char * with delimiters

I have an issue where I would like to take a string that is created from a function that has multiple lines where I need to get the all the new line delimiters for later formatting in Python.

For example:

const char * getInfoLogFunction()
{
    static char buffer[4096];
    glGetShaderInfoLog(shader, 4096, NULL, buffer);

    const char * compileStatus = buffer;
    return compileStatus
}

Now compileStatus points to a string such as:

This is a string.

With multiple lines.

Later I need to send compileStatus to an application that will put the entire string into 1 cell of tab separated table. With Python I then need to format the single line string back into multiple lines. Which I can do easily if the delimiters were in the string but they are not.

Is there a way I can get the string from compileStatus and have it formatted so it will have all the delimiters present?

I've found la number of examples when strings are created implicitly such as:

myString = R"xyz(Some String)xyz"

But I can't find a way to format a string referenced by const char * that was generated by a function.

thanks

Let's take a look at this code:

const char * getInfoLogFunction()
{
    static char buffer[4096];
    glGetShaderInfoLog(shader, 4096, NULL, buffer);

    const char * compileStatus = buffer; // <--- Here
    return compileStatus; 
}

This function returns compileStatus , which is a pointer to buffer . As a result, every time you call this function, you get back a pointer to the same character buffer. So, for example, if I say

const char* call1Result = getInfoLogFunction();

// Time passes, then...
const char* call2Result = getInfoLogFunction();

I'll have two pointers to the same buffer, so the string pointed at by call1Result will be exactly the same as the string pointed at by call2Result . This could cause real problems down the line if I wanted to store copies of all the logs over time, for example.

An easy way to fix this would be to have the function return a std::string , which makes a deep copy of the string used to initialize it. That means that future calls to getInfoLogFunction won't share the same underlying buffer. You can then pass it into Python by using the string::c_str() member function get a raw C-style array back.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM