Beckhoff C#从PLC读取字符串数组

时间:2014-12-02 12:18:26

标签: c# arrays string marshalling

我想问一下从Beckhoff 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 但我不知道它对我有帮助吗? 而且我不知道如何在我的情况下使用它。

1 个答案:

答案 0 :(得分:1)

谢谢Hans Passant的提示。

下面我展示方法 - 它工作正常,但我不得不使用循环来重写从struct到string []的文本。

可以添加一些内容吗?

    [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;
    }