lua里面序列化之后生成的字符串传到C#之后,经常会丢失数据,原因,序列化之后,字符串中会有特殊的字符,如果有"\0"那么这个字符串"\0"之后的数据丢失。我的解决方案是,在lua中把序列化之后的字符串中的每个字符转成byte,然后把这些字符再拼成字符串,每个byte占3个字节,新字符串中就没有特殊字符,在C#中,每次取3个字节转成byte。
lua部分:
local count = #str
local s = ""
for i = 1, count do
print("i>" .. string.byte(str, i, i) .. "<")
local t = string.byte(str, i, i)
if t < 10 then
s = s .."00"..t
elseif t < 100 then
s = s .. "0" .. t
else
s = s .. t
end
end
C#部分:
public static byte[] GetBytes(string s)
{
if (s.Length % 3 != 0)
{
Debug.LogError("ERROR");
return null;
}
int n = s.Length / 3;
byte[] tmp = new byte[n];
for (int i = 0; i < n; i++)
{
int idx = i * 3;
tmp[i] = byte.Parse(s.Substring(idx,3));
}
return tmp;
}