2014-12-02 1270 views
1

我想問一些關於從PLC Beckhoff讀取字符串數組的問題。Beckhoff C#從PLC中讀取字符串數組

我有閱讀Int16的一些方法 - 它工作正常

public Int16[] ReadArrFromPLC_Int16(string Mnemonic, int ArrLength) 
{ 
    Int16[] TempVariable = null; 

    try 
    { 
     ITcAdsSymbol itc = PLC3.adsClient.ReadSymbolInfo(Mnemonic); 
     long indexGroup = itc.IndexGroup; ; 
     long indexOffset = itc.IndexOffset; 

     int[] args = { ArrLength }; 
     TempVariable = (Int16[])PLC3.adsClient.ReadAny(indexGroup, indexOffset, typeof(Int16[]) , args); 
    } 
    catch (Exception ex) 
    { 
     MessageBox.Show(ex.Message, Mnemonic); 
    } 
    return TempVariable; 
} 

,但如果我想讀的字符串數組我得到一些例外:粗體的地方:「不能編組類型參數名稱類型。」 : ... adsClient.ReadAny(indexGroup,indexOffset,typeof(string []),args);

public string[] ReadArrFromPLC_String(string Mnemonic, int ArrLength) 
{ 
    string[] TempVariable = null; 

    try 
    { 
     ITcAdsSymbol itc = PLC3.adsClient.ReadSymbolInfo(Mnemonic); 
     long indexGroup = itc.IndexGroup; ; 
     long indexOffset = itc.IndexOffset; 

     int[] args = { ArrLength }; 
     TempVariable = (string[])PLC3.adsClient.ReadAny(indexGroup, indexOffset, typeof(string[]), args); 
    } 
    catch (Exception ex) 
    { 
     MessageBox.Show(ex.Message, Mnemonic); 
    } 
    return TempVariable; 
} 

我可以在循環中讀取數組,但需要很長時間。

我找到類似的主題: MarshalAsAttribute array of strings 但我不知道它對我有幫助嗎? ,我不知道如何在我的情況下使用它。

+0

你確定它不應該是一個字符數組? – jgauffin 2014-12-02 12:22:33

+1

ReadAny()要求使用[MarshalAs]聲明一個字符串以給該字符串一個固定大小。這可以防止字符串的數組工作。你可能做的最好的是聲明一個結構,每個成員一個字符串。 – 2014-12-02 12:40:06

+0

在PLC中,我聲明瞭一個數組「prg:ARRAY [0..200] OF STRING;」 - 標準長度的字符串= 80個字符。 (我可以聲明數組「prg:ARRAY [0..200] OF STRING [20];」 - 每個字符串中有20個字符) 該數組有201個元素。你能給我寫一下如何用[MarshalAs]創建這個結構嗎?我不知道如何使用它。 – Jarek 2014-12-02 13:08:52

回答

1

謝謝Hans Passant的小費。

下面我顯示方法 - 它工作正常,但我不得不使用循環,以重寫從結構到字符串[]的文本。

是可以添加的東西?

[StructLayout(LayoutKind.Sequential)] 
    public struct MyString 
    { 
     [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 21)] 
     //SizeConst = 21 because in my PLC I declared 
     //"prg : ARRAY[0..200] OF STRING[20];" 
     //(0 to 20 = 21 characters) 
     public string Str; 
    } 
    public string[] ReadArrFromPLC_String(string Mnemonic, int ArrLength) 
    { 
     MyString[] StrArrFromPLC = null; 
     try 
     { 
      ITcAdsSymbol itc = PLC3.adsClient.ReadSymbolInfo(Mnemonic); 
      long indexGroup = itc.IndexGroup; ; 
      long indexOffset = itc.IndexOffset; 
      int[] args = { ArrLength }; 
      StrArrFromPLC = (MyString[])PLC3.adsClient.ReadAny(indexGroup, indexOffset, typeof(MyString[]), args); 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.Message, Mnemonic); 
     } 
     string[] TempVariable = new string[StrArrFromPLC.Length]; 

     for(int i = 0; i < StrArrFromPLC.Length; i++) 
     { 
      TempVariable[i] = StrArrFromPLC[i].Str; 
     } 
     return TempVariable; 
    }