我正在尝试将 Lua 表转换为 C# 字节数组。我能够转换为 Double 数组以按如下方式工作:
> require 'CLRPackage'
> import "System"
> tbl = {11,22,33,44}
> dbl_arr = Double[4]
> dbl_arr:GetValue(0)
> dbl_arr:GetValue(1)
> for i=0,3 do Console.WriteLine(dbl_arr:GetValue(i)) end
0
0
0
0
> for i,v in ipairs(tbl) do dbl_arr:SetValue(v,i-1) end
> for i=0,3 do Console.WriteLine(dbl_arr:GetValue(i)) end
11
22
33
44
>
但是,如果我将 dbl_arr
更改为 Byte
数组 (dbl_arr = Byte[4]
),则会出现以下错误: (错误对象不是字符串)
我尝试了很多不同的方法,但都没有成功。任何帮助将不胜感激。
更新:
通过这样做,我能够从错误中获得更多信息:
suc,err = pcall(function() byte_arr:SetValue(12,0) end)
现在 suc
为假,err
返回以下消息:
SetValue failed
System.ArgumentException: Cannot widen from source type to target type either
because the source type is a not a primitive type or the conversion cannot
be accomplished.
at System.Array.InternalSetValue(Void* target, Object value)
at System.Array.SetValue(Object value, Int32 index)
我已经从 here 安装了 luaforwindows .它的版本是 5.1.4-45。我运行的是 Microsoft Windows XP Professional Version 2002 Service Pack 3
更新:
这是示例代码和错误发生的地方
> require 'CLRPackage'
> import "System"
> tbl = {11,22,33,44}
> dbl_arr = Byte[4]
> for i,v in ipairs(tbl) do dbl_arr:SetValue(v,i-1) end <-- Error occurs here
最佳答案
我怀疑原因是Console.WriteLine
没有采用 Byte
的重载。
我对 Lua 了解不够——在 C# 中我会调用 GetValue(i).ToString()
或 Convert.ToString(GetValue(i), 16)
并将该调用的结果提供给 Console.WriteLine
。
编辑 - 根据评论:
然后您需要转换为字节 - 在 C# 中我会做类似 dbl_arr:SetValue((Byte)0,4)
或 dbl_arr:SetValue((Byte)v,4 )
- 我不知道 Lua 是怎么做到的。
编辑 2 - 根据评论:
double
为 8 个字节,Single/float
为 4 个字节。
关于.net - 将表转换为字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7167229/