【发布时间】:2019-07-30 09:42:39
【问题描述】:
使用 TwinCAT 3 ADS.Net 从 PLC 读取,我试图读取包含结构数组的结构,但 ReadAny 命令因“无法编组类型”异常而崩溃。
不过,直接读取结构数组也可以。
public object ReadAny(long indexGroup, long indexOffset, Type type, int[] args);
ReadAny 方法的标头注释说: “如果要读取的对象的Type是数组类型,则必须在参数args中指定每个维度的元素个数。”
但是对于包含结构数组的结构,args 应该是什么? (没有 'args' 它也会失败。)
我目前使用 .NET 4.7,VS 2013。
有办法吗?
[StructLayout(LayoutKind.Sequential, Pack = 0)]
public class WholeData
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 5)]
public Station[] StationArray;
// Potentially more fields...
}
[StructLayout(LayoutKind.Sequential, Pack = 0)]
public class Station
{
[MarshalAs(UnmanagedType.I1)]
public bool isPass;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 81)]
public string name;
// More fields...
}
// -- Main --
int[] args = { 5 };
// Works fine:
Station[] stationArray = (Station[])m_AdsClient.ReadAny(indexGroup, indexOffset, typeof(Station[]), args);
// Fail:
WholeData wholeData = (WholeData)m_AdsClient.ReadAny(indexGroup, indexOffset, typeof(WholeData), args);
// - OR -
WholeData wholeData = (WholeData)m_AdsClient.ReadAny(m_VarHandle, typeof(WholeData), args);
【问题讨论】:
-
我猜这是某种内存错误,因为数组是引用类型(所以结构数组是引用)而结构是值类型(所以结构和结构数组是值而不是参考)
标签: c# arrays twincat twincat-ads-.net twincat-ads