开发者

Convert table to Byte array

I'm trying to convert a Lua Table to a C# Byte array. I was able to get a conversion to a Double array to work as follows:

> 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
>

However if I change the dbl_arr to a Byte array (dbl_arr = Byte[4]), then I get the following error: (error object is not a string)

I've tried a bunch of different things with no luck. Any help would be appreciated.

Update:

I was able to get a bit more information from the error by doing this:

suc,err = pcall(function() byte_arr:SetValue(12,0) end)

Now suc is false and err returns the following message:

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)

I've installed luaforwindows f开发者_如何学Gorom here. It's version 5.1.4-45. I'm running Microsoft Windows XP Professional Version 2002 Service Pack 3

Update:

This is the example code and where the error occurs

> 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


I suspect the reason is that Console.WriteLine does NOT have an overload that takes a Byte .

I don't know enough about Lua - in C# I would call GetValue(i).ToString() or Convert.ToString(GetValue(i), 16) and give the result of that call to Console.WriteLine.

EDIT - as per comment:

Then you need to convert to Byte - in C# I would do something like dbl_arr:SetValue((Byte)0,4) or dbl_arr:SetValue((Byte)v,4) - I don't know how this is done Lua.

EDIT 2 - as per comment:
double is 8 bytes, Single/float is 4 Bytes.


I found a workaround for this issue. I'll post it here, although I'm still curious why the above doesn't work.

Here is the workaround. I basically create a MemoryStream and use the WriteByte function to force the value to a Byte (since there is no overload of the function, it only accepts a byte). Then I call ToArray to get the byte[] from the MemoryStream:

> require 'CLRPackage'
> import "System"
> tbl = {11,22,33,44}
> mem_stream = MemoryStream()
> for i,v in ipairs(tbl) do mem_stream:WriteByte(v) end
> byte_arr = mem_stream:ToArray()
> for i=0,byte_arr.Length-1 do Console.WriteLine(string.format("%d", byte_arr:GetValue(i))) end
11
22
33
44
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜