C# tolua 之间互传 byte[]

(金庆的专栏 2020.8)

lua中不区分 string 和 byte[], 而在 C# 中 string 和 byte[] 之间转换涉及编码。

C# 中一般这样转:

string类型转成byte[]:

byte[] byteArray = System.Text.Encoding.Default.GetBytes(str);

byte[]转成string:

string str = System.Text.Encoding.Default.GetString(byteArray);

Default 编码是本机当前所用编码,还可以用 ASCII, UTF8 等其他编码。

测了在 lua 中读入一块2进制数据,调用 tolua 导出的一个方法,如:

public void Print(string s)
{
    byte[] buf = Systen.Text.Encoding.Default.GetBytes(s);
    Debug.Log(Bitconvert.ToString(buf));
}

测了 Default, ASCII, UTF8, ISO-8859-1(Latin-1), Unicode 发现得到的 byte[] 会出错。

也试了 C#中使用Buffer.BlockCopy()方法将string转换为byte array的方法 发现 tolua 传到 C# 的 string 已经是编码过的,直接复制也是错的。

xlua 也有相同问题,Unity xlua 从lua传递byte[]数据到C# 使用 MemoryStream对象来传递byte[]数据,确实有点绕。

tolua 中有个 LuaByteBuffer,可以用来传递 byte[].
tolua#中的LuaByteBuffer类

从 lua 传 byte[] 到 C#, 只需要将参数 string 改为 LuaByteBuffer:

public void Print(LuaByteBuffer luaByteBuffer)
{
    byte[] buf = luaByteBuffer.buffer;
    Debug.Log(Bitconvert.ToString(buf));
}

更正确又简单的方法是用 LuaByteBufferAttribute:

[LuaByteBufferAttribute]
public void Print(byte[] buf)
{
    Debug.Log(Bitconvert.ToString(buf));
}

最终发现不需要 LuaByteBufferAttribute,直接用 byte[] 就行:

public void Print(byte[] buf)
{
    Debug.Log(Bitconvert.ToString(buf));
}

C# 传 byte[] 到 lua, 默认为 “System.Byte[]”(userdata),可以用 tostring() 转为 lua string:

s = tolua.tolstring(result)

如果可以,应该给数据加上标签[LuaByteBufferAttribute],这样传到 lua 就是 string。
或者在C#建一个LuaByteBuffer把byte[]传给lua。