如何使用libnodave从PLC读取/写入结构

问题描述 投票:1回答:1

我正在编写一个小的c#应用程序,它将一些数据读/写到S7-300 PLC的DB存储器中。我正在使用PLCSim模拟器和DotNetSiemensPLCToolBoxLibrary来执行一些测试。如你所知DotNetSiemensPLCToolBoxLibrary是一个超过libnodave的层,所以我经常直接使用libnodave。我可以通过PLC连接成功,我可以写/读输入,merker和字符串。但是当我尝试编写/读取结构时,我遇到了问题。以下是在plc中编写结构的代码:

//PLCTagGeneric
PLCTag<TestStruct> tst = new PLCTag<TestStruct>() { DataBlockNumber = 1, ByteAddress = 0 };
tmpConn.ReadValue(tst);
TestStruct read = tst.GenericValue;
TestStruct wrt = new TestStruct();
wrt.bb = 1;
wrt.cc = true;
wrt.ee = 14;           
wrt.test = "Bin da!";
tst.Controlvalue = wrt;
tmpConn.WriteValue(tst);

这是阅读代码:

PLCTag<TestStruct> tst = new PLCTag<TestStruct>() { DataBlockNumber = 1, ByteAddress = 0 };
tmpConn.ReadValue(tst);

byte[] buf = new byte[18];
int res = tmpConn._dc.readBytes(libnodave.daveDB, 1, 0, 18, buf);
tst._readValueFromBuffer(buf, 0);
TestStruct t = tst.GenericValue; 

这是结构:

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public struct TestStruct
    {
        public SByte bb;
        public Boolean cc;
        public UInt32 ee;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 10)]
        public string test;
    }

阅读的输出是:

bb: 0
ee: 920583
cc: false
test: n da!

为什么?我需要帮助。谢谢

c# struct libnodave
1个回答
1
投票

解决了。在PLC中,数据只是一个字节流。因此,如果您编写一个Int16 | Int32 | string序列,则必须以相同的顺序读取,否则将导致解析字节时出错。希望这可以帮助

© www.soinside.com 2019 - 2024. All rights reserved.