.net - 将表转换为字节数组

标签 .net arrays lua luainterface clrpackage

我正在尝试将 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/

相关文章:

PHP - 数组中的 Strpos

string - 使用lua解析代码语法?

lua - 如何迭代Lua字符串中的单个字符?

c# - 以 .NET 2.0 为目标时使用(某些)lambda 表达式?

c# - 将库重构为异步,如何避免重蹈覆辙?

.net - Web 浏览器组件的一个很好的替代品?

javascript - 获取数组元素的索引号

c# - 图像和样式未出现在 HTML 电子邮件中

c++ - 什么是数组中元素的前身?我如何找到它?

lua - 找不到模块 'cudnn' :No LuaRocks module found for cudnn