I have encountered a strange bug while trying to get a NSString from a const char *.
// in my obj c class
void myObjCMethod {
const char* charString = myCFunctionReturningConstCharPtr();
printf("%s \n", charString); // prints the correct string
// ...put a brakpoint here...
NSString * nsString1 = [NSString stringWithUTF8String:charString];
NSLog(@"%@", nsString1); // prints nothing
NSString * nsString2 = [NSString stringWithFormat:@"%s",charString];
NSLog(@"%@", nsString2); // prints nothing either
}
The const char coming from my c method prints nicely to the console. But trying to convert to NSString results in an empty string. Now the weirdest thing is, that when I try to debug the code and set a breakpoint (as indicated above), my NSString suddenly becomes valid!
So what -- my mesurement changes the result? Sounds familiar from physics class long ago, but I doubt there is quantum mechanics involved here.
Note:
I have omitted the implementation of myCFunctionReturningConstCharPtr() for now, as it would add another layer of complexity that is probably not related to the present problem (There are multiple c++ libraries involved, the string has been converted from char pointer to std::string and back).
I've been banging my head against this for two days now, any help is appreciated very much! Thanks
EDIT:
The string initially comes from the struct SPODNode from PowerVR's Insider SDK.
There we have:
struct SPODNode {
PVRTchar8 *pszName;
// ...
}
With:
typedef char PVRTchar8;
In my code I do:
std::string MyCppClass::pvrNodeName() {
if (node && node->pszName) {
string stdName(node->pszName);
return stdName;
}
return string();
}
And finally in myCFunctionReturningConstCharPtr():
const char * myCFunctionReturningConstCharPtr() {
std::string stdString = myCppClassInstace->pvrNodeName()
return stdString.c_str();
}
I hope that helps!
myCFunctionReturningConstCharPtr(). Could you show it? - Andy Prowlconst char*is returned. In particular, whether it is obtained from a localstd::stringobject through a call todata()orc_str(). - Andy ProwlstringWithUTF8Stringfails if the string is not correct UTF-8. - Martin R