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!

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

4

1 回答 1

1

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

于 2014-08-04T19:47:12.583 回答