上週在項目開發中遇到一個奇怪的問題,某個c++模塊解壓完的字節流數據傳遞給lua後,lua在作基於字節流的反序列化時始終出錯,剛開始覺得是否是c++模塊讀取出來的字節流有問題,可是debug發現,c++拿到的字節流確實是正確的,因而跑到lua的接口中打印了字節流的內容和長度發現,在某些狀況下C++中打印出來的字節流和lua拿到的字節流的長度不等,忽然想起多是lua和C++對string的支持不一樣致使的.由於C++中沒有字節這個類型,因此存儲字節流就通常存儲到以char類型結構爲基礎類型的數組或者std::string中,可是這時,若是對char數組或者std::string進行strlen相似的操做,則會存在隱患,由於strlen認爲遇到'\0'字節就結束了,而若是存儲在char數組中的字節流剛好是中間含有'\0'這個字節的話,則得出來的長度就有問題了;可是在lua中,string中含有'\0'是不會有問題的, 由於它求長度並非簡單的調用strlen,而是lua本身實現了strlen函數, 因此即便是拿到含有'\0'字符的字節流字符串, 也不會出現錯誤.c++
進過調試,發現確實是這裏的問題,因而更改了cocos2d-x中 CCLuaStack中pushCCLuaValue函數中的代碼即解決了上述問題,代碼以下(注意註釋的部分, 被註釋的部分爲cocos2d-x原來的代碼): void CCLuaStack::pushCCLuaValue(const CCLuaValue& value) { const CCLuaValueType type = value.getType(); if (type == CCLuaValueTypeInt) { return pushInt(value.intValue()); } else if (type == CCLuaValueTypeFloat) { return pushFloat(value.floatValue()); } else if (type == CCLuaValueTypeBoolean) { return pushBoolean(value.booleanValue()); } else if (type == CCLuaValueTypeString) { return pushString(value.stringValue().c_str(), value.stringValue().length()); // return pushString(value.stringValue().c_str()); cocos2dx的bug } else if (type == CCLuaValueTypeDict) { pushCCLuaValueDict(value.dictValue()); } else if (type == CCLuaValueTypeArray) { pushCCLuaValueArray(value.arrayValue()); } else if (type == CCLuaValueTypeCCObject) { pushCCObject(value.ccobjectValue(), value.getCCObjectTypename().c_str()); } }數組