2011-08-23 132 views
3

我試圖將一個Lua錶轉換爲一個C#字節數組。我能得到一個轉換爲雙陣列工作方式如下:將錶轉換爲字節數組

> 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_arrByte陣列(dbl_arr = Byte[4]),然後我得到了以下錯誤:(error object is not a string)

我我試了一堆不同的東西,但沒有運氣。任何幫助,將不勝感激。

更新:

我能夠這樣做是爲了得到錯誤更多的信息:

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專業版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 
+0

哪裏'dbl_arr'從何而來? –

+0

@Nicol - 它只是我創建的Double數組:'dbl_arr = Double [4]' – SwDevMan81

+0

不夠公平。我的意思是'Double [4]'來自哪裏。它是否使用某種metatable來使用[]創建對象? –

回答

0

我找到了解決此問題的解決方法。我會在這裏發佈,雖然我仍然很好奇爲什麼上述不起作用。

這是解決方法。我基本上創建一個MemoryStream並使用WriteByte函數強制值爲一個字節(因爲沒有函數的重載,它只接受一個字節)。然後,我打電話ToArray得到來自MemoryStreambyte[]

> 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

我懷疑的原因是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字節。

+0

這就是迴應,我應該提到運行for循環嘗試和'SetValue'時發生錯誤。它會打印所有0的罰款,但是當我嘗試做'dbl_arr:SetValue(0,4)'之類的東西時,我得到了'(錯誤對象不是字符串)'消息 – SwDevMan81

+0

ok - 請參閱上面的編輯 – Yahia

+0

是的,不幸的是沒有一種方法可以施放。我試着做'Convert.ToByte(4)'並將其傳入,但仍然失敗。我有一種感覺,它將中間結果存儲爲Lua'數字',然後自動將它轉換爲C#'Double'。這是我可以根據這個錯誤提出的唯一解釋。 – SwDevMan81