For reasons beyond my control, I need to return const char* from a function, but I don’t know what the chars need to be at compile time. My solution is something like the following:
const char* __str__() {
static std::string String;
String = [some fancy stuff];
return String.c_str();
}
The static prevents the string’s destruction on exiting the function, but it also means that the memory sticks around until my program exits (right?). Because the returned string can occasionally be huge (GBs), this can be a real problem.
I usually avoid pointers at all costs and only ever use static for class members, so I’m not 100% sure what I’m doing. Is this guaranteed to work? Is there a better way?
[The context of this question is printing a complicated object in python, using the __str__ method. I define the method in my c++ code, which is then wrapped by SWIG. The SWIG example shows the use of static, but it’s not clear to me that that’s the only way. I am open to suggestions.]
As @Prætorian said, SWIG can return std::string to Python. Here’s an example from the SWIG example I think you are looking at. Also shown is a way to avoid using a reserved name in C++:
x.i
x.h
Output