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

本文关键字:字符串 数组 读取 PLC Beckhoff | 更新日期: 2023-09-27 18:32:43

我想问一下从PLC Beckhoff读取字符串数组的问题。

我有一些读取 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;
}

我可以循环读取数组,但需要很长时间。

我发现了类似的主题:元送As字符串的属性数组但我不知道它对我有帮助吗?我不知道如何在我的情况下使用它。

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

谢谢Hans Passant的提示。

下面我展示了方法 - 它工作正常,但我必须使用循环才能将文本从结构重写为 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;
    }