I am using google protocol buffer to send and receive data in cocos2d-x multiplayer game via Google Play Games Services iOS sdk.
Protocol buffer converts data to std::string but GPGS iOS sdk sends data via NSData hence I have to convert from std::string to NSData and then back to std::string after receiving data.
I am currently using following method:
( std::string to NSData and NSData to std::string will be done in different functions at different times. Following code just summarise what I am doing overall)
//PlayerData is protocol buffer class
PlayerData data, temp;
std::string dataStr;
data.SerializeToString(&dataStr);
NSString* nsDataStr = [NSString stringWithCString:dataStr.c_str()
encoding:[NSString defaultCStringEncoding]];
NSData* nsData = [nsDataStr dataUsingEncoding:NSUTF8StringEncoding];
NSString* dataStr_2 = [[NSString alloc] initWithData:nsData
encoding:NSUTF8StringEncoding];
std::string foo = [dataStr_2 UTF8String];
temp.ParseFromString(foo);
Initial string ie dataStr after serializing
"\\r\\x95n\\x99D\\x158\\xddNDJ\\nUmar SaeedR\\x12p_CPH64oqq2K-TXxAB"
size: 42
Final string ie foo before parsing
"\\r\\xc3\\xafn\\xc3\\xb4D\\x158\\xe2\\x80\\xbaNDJ\\nUmar SaeedR\\x12p_CPH64oqq2K-TXxAB"
size: 46
the ParseFromString function of protocol buffer does not parse foo and returns false.
How to do string conversions so that string remains same?
I know this is old, but... Could you use protobufs ParseFromArray instead of ParseFromString?
IE
const void *bytes = [parseData bytes];
int byteLen = (int)[parseData length];
protobufMessage.ParseFromArray(bytes, byteLen);
Just a thought.
Try this:
std::string str = "123";
NSData *data = [NSData dataWithBytes:str.data() length:str.length()];
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.