Skip to main content

Structure Decoding (StructDecoder)

Overview​

OPC UA 1.04+ Place the field definitions for each custom structure into the node’s DataType DataTypeDefinition attribute (AttributeId=27, Part 5 §6.4.2).The design flow is as follows: the client reads this property → retrieves StructureDefinition (Fields[]) → caches it; after obtaining the ExtensionObject binary data, it deserializes it into a dictionary 字段名 → 值 using UA Binary encoding (Part 6 §5.2) in field order.

Current Status (Must Read): Decode(Variant) NowReturns only the diagnostic dictionary; does not return field values, DecodeBody Always returns null. For details, see “Implementation Limitations” at the end of this document; please read it thoroughly before deciding whether to integrate this feature.

The decoding rules cover the following patterns (since we currently cannot obtain the ExtensionObject byte stream and field definitions, we cannot proceed to the decoding step):

  • All basic types (Boolean / Int / Float / Double / String / DateTime / Guid / ByteString / NodeId / ExpandedNodeId / StatusCode / QualifiedName / LocalizedText / XmlElement)
  • Nested Structures (A field DataType points to another custom structure; automatic recursion)
  • Enumeration (Decoded Int32 by )
  • Arrays (ValueRank ≥ 1)
  • Union (1-based selector)
  • Optional field (UInt32 EncodingMask)
  • Maximum recursion depth: 32 levels + circular reference detection (throws an exception if exceeded InvalidDataException; does not cause a stack overflow or process crash)

API​

MembersCategoryReading and WritingNote
new StructDecoder(ua)Structure—Bound to Session (ua == null Throw ArgumentNullException)
decoder.Decode(Variant v)MethodsReadDecode ExtensionObject, Returns Dictionary<string, object>
decoder.Decode<T>(Variant v)MethodsReadDecode to Strongly Typed T (Fields Mapped by Name)
decoder.DecodeBody(byte[] body, string dataTypeNodeId)MethodsReadDirectly feed the byte stream + DataType decode
decoder.ClearCache()Methods—Clear the field table cache (call this when changes are made DataType on the server)
decoder.CachedDefinitionCountPropertiesReadNumber of cached structures
StructDecoder.StatusKeyConstants—"_status", Diagnostic Field Name
StructDecoder.TypeIdKeyConstants—"_typeId", Diagnostic Field Name

Authentic signature:

public sealed class StructDecoder
{
public const string StatusKey = "_status";
public const string TypeIdKey = "_typeId";

public StructDecoder(DarraOpcUa ua);

public void ClearCache();
public int CachedDefinitionCount { get; }

public Dictionary<string, object> Decode(Variant v);
public T Decode<T>(Variant v) where T : new();
public Dictionary<string, object> DecodeBody(byte[] body, string dataTypeNodeId);
}

Return Value Conventions:

CallNot ExtensionObject / Input parameter is nullYes ExtensionObject
Decode(Variant)nullA _status dictionary containing only (no byte stream is currently available)
Decode<T>(Variant)default (T At the time of class formation null)An empty new T() instance — All fields have default values
DecodeBody(...)nullnull (Field definition parsing is not yet enabled)
Don't mistake an empty instance of Decode<T> for success.

For Decode<T>, when T is a class null simply means "not an ExtensionObject"; a T that is non-null but has every field at its default means the ExtensionObject branch was taken without the fields being decoded. Decide success by checking whether the Decode(Variant) dictionary contains the _status field — not by checking whether Decode<T> is null.

Related Structures:

public sealed class StructDefinition
{
public string Name { get; set; } // Structure Name (DataType Node BrowseName)
public string DataTypeId { get; set; } // DataType NodeId (String format)
public string BaseDataType { get; set; } // Parent Type NodeId
public StructureKind Kind { get; set; } // Structure type, default: Structure
public List<StructField> Fields { get; set; } // Field Table (Order = Binary Encoding Order)
public string DefaultEncodingId { get; set; } // Binary Encoding Node NodeId
public bool IsUnion { get; } // Is it Union-coded? (Prefix selector)
public bool HasOptionalFields { get; } // Whether to include the "Optional" field (prefix EncodingMask)
}

public sealed class StructField
{
public string Name { get; set; } // Field Name
public string Description { get; set; } // Field Description (LocalizedText the "Text" section)
public string DataType { get; set; } // Field Type NodeId
public int ValueRank { get; set; } // -1 scalar / 0 one-dimensional or higher / 1+ array; default -1
public uint[] ArrayDimensions { get; set; } // Upper Limit per Dimension
public uint MaxStringLength { get; set; } // String/ByteString/XmlElement Maximum length (0 = unlimited)
public bool IsOptional { get; set; } // Optional field marker
}

public enum StructureKind
{
Structure = 0, // Normal, Fixed Order
StructureWithSubtypedValues = 1, // Fields containing sub-types (coded the same as Structure)
StructureWithOptionalFields = 2, // Includes optional fields, prefix UInt32 EncodingMask
Union = 3, // Union, prefix UInt32 selector (1-based, 0=null)
UnionWithSubtypedValues = 4 // Union with subtypes (coded the same as Union)
}

Code Example​

using System;
using System.Collections.Generic;
using DarraOpcUa_Client;

using var ua = new DarraOpcUa("opc.tcp://localhost:4840");
ua.Connect();

var dec = new StructDecoder(ua);

// 1) Read a node containing a custom structure (for example: Robot.CurrentPose PoseType)
using var dv = ua.Read("ns=2;s=Robot.CurrentPose");

// Currently, Decode only returns a diagnostic dictionary—use it to _status determine whether the field has actually been decoded.
var fields = dec.Decode(dv.Value);
if (fields == null)
{
Console.WriteLine("不是 ExtensionObject");
}
else if (fields.TryGetValue(StructDecoder.StatusKey, out var diag))
{
Console.WriteLine($"暂不可用: {diag}");
}
else
{
foreach (var (name, value) in fields)
Console.WriteLine($"{name} = {value}");
}

// 2) Strongly typed — Note: At this point, you will receive an empty instance with all fields set to their default values; this should not be interpreted as success.
var pose = dec.Decode<PoseType>(dv.Value);
if (pose != null) Console.WriteLine($"x = {pose.X}");

// 3) Use this when you already have the raw bytes DecodeBody
// (Currently, the constant returns null)
byte[] rawBody = LoadExtensionObjectBody(); // The `body EO ` obtained by the caller
var dict = dec.DecodeBody(rawBody, "ns=2;i=3001");

// 4) Cache Management
Console.WriteLine($"已缓存结构体定义 = {dec.CachedDefinitionCount}");
dec.ClearCache();

PoseType This is written by the caller POCO; the field names must match those on the server (mapped by name; if there is no match, the field is skipped):

public class PoseType
{
public double X { get; set; }
public double Y { get; set; }
public double Z { get; set; }
}

Implementation Constraints​

Current VersionStill can't retrieve the field value, As described in the call path:

  1. Decode(Variant) Do not return the field — If the ExtensionObject TypeId or Body cannot be obtained, it always returns a _status dictionary (StructDecoder.StatusKey) containing only.
  2. DecodeBody(byte[], string) Heng Returns null — When reading StructDefinition, if you can't DataTypeDefinition get it, you can't parse the fields without a field table.
  3. Decode<T> The Trap of Empty Instances — See the warning API below the table above.

Available sections:

  • Recursion depth limit: 32 levels; if exceeded, throw an exception InvalidDataException
  • Circular Reference Detection (A→B→A) — If the same recursion DataType occurs, an exception is thrown immediately. InvalidDataException
  • ClearCache() / CachedDefinitionCount Cache Management Interface

BuiltinType.DiagnosticInfo Decoding is not supported.

Best Practices​

  • Share a decoder instance — The field table cache is persisted with the instance; one cache is maintained per session.
  • Evaluate First, Then _status Use the Field — See Step 1 of the code example; do not assume that the field has already Decode been returned
  • Decode<T> The field POCO names are aligned with the server-side field names — Maps by name; mismatched fields are silently skipped
  • Server-side If the DataType definition changes, you need to ClearCache() — The cache does not expire automatically

Cross-Language Comparison​

C#PythonJavaC++RustC
StructDecoderStructDecoderStructDecoderStructDecoderStructDecoderDarraUa_StructDecoder
DecodedecodedecodeDecodedecodeDarraUa_StructDecoder_Decode

Decode<T> / DecodeBody / ClearCache / CachedDefinitionCount In C#, these correspond to Python's decode_typed / decode_body / clear_cache /, respectively cached_definition_count.

Next Step​