Skip to main content

PDO inputs and outputs

Access the process image through slave.PDO​

A PDO is one segment of the process image, exchanged automatically by the master every cycle. Once mapped to a struct, reading or writing a member reads or writes the process image itself — zero-copy: no copying, no refreshing; reads always see the current cycle, and writes go out in the next cycle.

PDO cycle and mailbox

Mailbox communication (SDO/CoE/FoE and so on) rides along with the PDO cycle automatically and does not consume an extra frame. Mailbox responses take about 2 PDO cycles.

Struct contract
  • Must be [StructLayout(LayoutKind.Sequential, Pack = 1)], with field order matching the PDO mapping byte for byte; omitting Pack = 1 adds alignment padding and shifts every field (it still compiles, and you silently read dirty data).
  • Must not exceed the byte count for the corresponding direction (slave.InputsByteCount / slave.OutputsByteCount).
    • InputsMapping<T>() / OutputsMapping<T>() throw InvalidOperationException when the struct is oversized.
    • The slice variants throw ArgumentOutOfRangeException when the offset goes out of range.
    • Overloads with onChanged do not check the size when mapping; a mismatch only surfaces on a later read.
    • A smaller struct is valid and covers the image from the given offset.
  • Only fixed-size value types are allowed: reference fields (string / arrays / delegates) throw InvalidOperationException (overloads with onChanged skip this check). Decode strings from the whole-frame Inputs.
  • A bool field is not bit0 on the zero-copy ref mapping path: C# interprets the struct field itself, applying the language's own rule that a value other than 0 is true. For a non-canonical byte such as 0x02 / 0x80, the ref mapping reads true while the element view AsBool reads false. Use slave.PDO.In[i].AsBool when you need bit0, or the bitwise GetBit / SetBit. Exception: the ValueSnapshot path normalizes the bool byte by bit0 before interpreting it, matching AsBool.
  • A mapping stays valid once made; Close / a generation change invalidates the old ref, so map again when you re-enter OP.
    • A generation change raises no notification, so an old ref cannot tell that it is stale. When you take a ref, store slave.ProcessImageGeneration alongside it and compare before use: a different value means the generation changed, and the old ref must be discarded and remapped.
    • The value increases monotonically (starts at 1, never returns 0) and is readable from any thread; Close and re-applying the DC / ENI configuration increment it by 1. The value does not change during PreOp→SafeOp, so always map again when you re-enter OP.

Usage examples​

Day-to-day usage​

① Map to a struct (zero-copy, keep using it): map once after entering OP, get a ref pinned to the process image, then read and write it like a variable.

using System.Runtime.InteropServices;
using DarraEtherCAT_Master;

[StructLayout(LayoutKind.Sequential, Pack = 1)] // Pack = 1 is required; field order matches the PDO byte for byte
public struct InPdo { public ushort StatusWord; public int ActualPosition; }

[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct OutPdo { public ushort ControlWord; public int TargetPosition; }

using var master = new DarraEtherCAT()
.SetENI(@"C:\EtherCAT\MyProject.deni") // one-line DENI load
.Build()
.Master;
master.SetState(EcState.OP, out _); // enter OP

var slave = master.Slaves[0];

ref readonly InPdo input = ref slave.PDO.InputsMapping<InPdo>(); // map once (after entering OP)
ref OutPdo output = ref slave.PDO.OutputsMapping<OutPdo>();

output.ControlWord = 0x000F; // write: sent in the next cycle
output.TargetPosition = 10000;
Console.WriteLine($"status=0x{input.StatusWord:X4} pos={input.ActualPosition}"); // read: current cycle

② Single read (one-shot): skip the struct and take just one copy of the current value.

// single point: take an element view at a byte offset (an out-of-range index throws IndexOutOfRangeException)
int pos = slave.PDO.In[2].AsInt32; // 4 bytes starting at offset 2
ushort sw = slave.PDO.In[0].AsUInt16; // 2 bytes starting at offset 0 (StatusWord)

// whole segment: a complete input frame snapshot, consistent within a cycle, and it does not follow the bus once copied
byte[] frame = slave.PDO.Inputs;
string name = System.Text.Encoding.ASCII.GetString(frame, 6, 16).TrimEnd('\0'); // string field
Console.WriteLine($"status=0x{frame[0] | (frame[1] << 8):X4} name={name}");

Cyclic changes​

One mapping is enough; put the same mapping into your own cyclic loop (or a scheduling point inside it) and use it directly:

This is a polling example on a user thread, not a deterministic motion cycle

The cadence of Thread.Sleep is set by the operating system scheduler, so jitter and phase are outside the bus's control. CSP / synchronized axes must hook master.Events.ProcessDataCyclicSync, which paces them from the PDO cycle. Do not send motion targets (target position, control-word enable bits) directly from a polling thread either; any beat mismatch with the bus cycle causes jitter. The pattern below is only suitable for status monitoring and non-realtime IO.

using System.Threading;

while (running)
{
output.ControlWord = (input.StatusWord & 0x0004) != 0 ? (ushort)0x000F : (ushort)0x0006;
output.TargetPosition = input.ActualPosition;
Thread.Sleep(1); // polling cadence on a user thread, not a motion cycle; hook ProcessDataCyclicSync for motion
}

The master moves process data every cycle: reads in your loop always see the current cycle and writes are sent in the next cycle, with no extra calls. Do not map again on every cycle either (Close / a generation change is what invalidates an old ref; mapping once more when you re-enter OP is enough).

Struct mapping (zero-copy)​

InputsByteCount / OutputsByteCount​

Byte counts of the current slave's input / output process image, used to check the struct size before mapping.

public int InputsByteCount  { get; }
public int OutputsByteCount { get; }

Return value:

  • int — input / output process image byte count; 0 when OP has not been entered or nothing is mapped

Description: these two properties are declared on Slave (slave.InputsByteCount), not on slave.PDO. The value is throttled to about 50 ms, so shortly after a state change it may still show the previous cycle's value.

Example:

using System.Runtime.CompilerServices;

if (Unsafe.SizeOf<InPdo>() > slave.InputsByteCount)
throw new InvalidOperationException("结构体大于输入 PDO"); // (SDK output, = struct larger than input PDO)

Unsafe.SizeOf<T>() measures by the real struct layout (same basis as sizeof). For structs containing bool / char, do not substitute Marshal.SizeOf — it measures by the marshaled layout and may give a different result. It is built in on .NET Core 3.0+, while .NET Framework / netstandard2.0 need the System.Runtime.CompilerServices.Unsafe package.

InputsMapping<T>()​

Maps the input process image (TxPDO) to a read-only struct reference pinned to the process image; after one mapping, reading a field reads the current cycle value (zero-copy, not a snapshot).

public ref readonly T InputsMapping<T>() where T : struct

Return value:

  • ref readonly T — read-only reference pinned to the process image, readable from any thread

Description:

  • Call it after entering OP.
  • The I area is overwritten by the master every cycle, so writes to it are silently ignored; use OutputsMapping<T>() to write process data.
  • Throws InvalidOperationException when the process image is unavailable (OP not entered).
  • Throws PdoInputStaleException (derived from InvalidOperationException) when the slave is offline (slave.IsLost): the image holds the last frame from before the drop, so it must not be delivered as the current value.
  • Throws ObjectDisposedException when the Slave has been disposed (after Close()).
  • Throws InvalidOperationException when 结构体大于输入 PDO (SDK output, = struct larger than input PDO).

Example:

ref readonly InPdo input = ref slave.PDO.InputsMapping<InPdo>();
ushort status = input.StatusWord; // current cycle value

InputsMapping<T>(onChanged)​

Maps to a struct instance and attaches a data-change callback. When you only want the ref, call the overload without onChanged; no extra binding API is needed.

public Slave.InputPdoInstance<T> InputsMapping<T>(Action<Slave.PdoStructChangedEventArgs<T>> onChanged) where T : struct
public Slave.InputPdoInstance<T> InputsMapping<T>(Action onChanged) where T : struct

Return value:

  • InputPdoInstance<T> — .Value is a ref readonly T pinned to the process image (zero-copy); .ValueSnapshot is a snapshot of the current value (it does not change on its own)

Callback parameters:

public sealed class PdoStructChangedEventArgs<T> : EventArgs where T : struct
{
public ushort SlaveIndex { get; } // slave index
public bool IsInput { get; } // whether this is an input PDO
public T Previous { get; } // value before the change
public T Current { get; } // value after the change
public DateTime Timestamp { get; } // timestamp
}

Description: the SDK continuously compares the complete frame in the background without consuming PDO cycles; the callback runs only when the struct value changes.

Example:

var input = slave.PDO.InputsMapping<InPdo>(e =>
Console.WriteLine($"位置变化: {e.Previous.ActualPosition} -> {e.Current.ActualPosition}")); // Position change: {e.Previous.ActualPosition} -> {e.Current.ActualPosition}

int pos = input.Value.ActualPosition; // zero-copy, current cycle
InPdo snap = input.ValueSnapshot; // snapshot, does not follow the bus

InputsSliceMapping<T>(int offset)​

Maps a read-only struct reference at the given byte offset in the input process image, for devices such as MDP units whose modules are laid out as separate segments.

public ref readonly T InputsSliceMapping<T>(int offset) where T : struct

Parameters:

  • offset (int) — byte offset from the start of this slave's input process image

Return value:

  • ref readonly T — read-only reference pinned at that offset (zero-copy)

Description: a negative offset, or an offset + Unsafe.SizeOf<T>() past the end, throws ArgumentOutOfRangeException (the size uses the real struct layout; for structs containing bool/char, do not substitute Marshal.SizeOf).

An unavailable process image (OP not entered) throws InvalidOperationException; an available image on an offline slave throws PdoInputStaleException (derived from InvalidOperationException). The staleness guard matches InputsMapping<T>() and holds only at the moment the ref is taken: callers that cache the ref beyond the cycle and keep dereferencing it after a drop must re-check with slave.IsLost.

Related structures:

using System.Runtime.InteropServices;

[StructLayout(LayoutKind.Sequential, Pack = 1)] // Pack = 1 is required; omitting it adds alignment padding and shifts fields
public struct Module1In // module 1: occupies input image offsets 0-7 (8 bytes in total)
{
public ushort StatusWord; // offset 0
public ushort ErrorCode; // offset 2
public int Value; // offset 4
}

[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct Module2In // module 2: input image starts at offset 8
{
public ushort StatusWord; // offset 8
public ushort ErrorCode; // offset 10
public int Value; // offset 12
}

[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct Module2Out // module 2: output image starts at offset 8
{
public ushort ControlWord; // offset 8
public int Setpoint; // offset 10
}

The byte width of each struct must match the PDO length of the corresponding module; here module 1 occupies 8 bytes, so module 2 starts at offset 8.

Example:

// MDP device: module 1 starts at offset 0, module 2 at offset 8
ref readonly Module1In mod1 = ref slave.PDO.InputsSliceMapping<Module1In>(0);
ref readonly Module2In mod2 = ref slave.PDO.InputsSliceMapping<Module2In>(8);

InputsSliceMapping<T>(int offset, onChanged)​

Maps a struct instance at the given offset in the input process image and attaches a data-change callback.

public Slave.InputPdoInstance<T> InputsSliceMapping<T>(int offset, Action<Slave.PdoStructChangedEventArgs<T>> onChanged) where T : struct
public Slave.InputPdoInstance<T> InputsSliceMapping<T>(int offset, Action onChanged) where T : struct

Parameters:

  • offset (int) — byte offset from the start of this slave's input process image
  • onChanged — data-change callback, with the same parameters as above

Example:

var mod2 = slave.PDO.InputsSliceMapping<Module2In>(8, e =>
Console.WriteLine($"模块 2 数据变化: {e.Previous} -> {e.Current}")); // Module 2 data change: {e.Previous} -> {e.Current}

ref readonly Module2In m2 = ref mod2.Value; // zero-copy

OutputsMapping<T>()​

Maps the output process image (RxPDO) to a struct reference; changing a field writes to the bus.

public ref T OutputsMapping<T>() where T : struct

Return value:

  • ref T — writable reference pinned to the process image (zero-copy); field changes are sent to the slave in the next cycle

Description: throws InvalidOperationException when 结构体大于输出 PDO (SDK output, = struct larger than output PDO); an unavailable process image or a disposed Slave behaves as in InputsMapping<T>().

Example:

ref OutPdo output = ref slave.PDO.OutputsMapping<OutPdo>();
output.ControlWord = 0x000F; // sent in the next cycle

OutputsSliceMapping<T>(int offset)​

Maps a writable struct reference at the given byte offset in the output process image.

public ref T OutputsSliceMapping<T>(int offset) where T : struct

Parameters:

  • offset (int) — byte offset from the start of this slave's output process image

Example:

ref Module2Out mod2 = ref slave.PDO.OutputsSliceMapping<Module2Out>(8);
mod2.Setpoint = 1500;

Input process image pointer and freshness​

InputsPtr / TryGetInputsPtr are declared on Slave (slave.InputsPtr), not on slave.PDO. All three zero-copy input entry points share one freshness guard: after a slave goes offline, the I area keeps the last frame from before the drop (the "input stays stable" convention), so the address and length are still there but those bytes are no longer the current value.

InputsPtr​

public IntPtr InputsPtr { get; }

Start address of the input process image (TxPDO); the same process image that slave.PDO.InputsMapping<T>() exposes.

Return value:

  • IntPtr — start address of the input process image

Description:

  • Read-only direction: the I area is overwritten by the master every cycle, so writes to it are silently ignored; use OutputsPtr to write process data.
  • Throws InvalidOperationException ("PDO input image unavailable") when the image is unavailable (not mapped / OP not entered).
  • Throws PdoInputStaleException when the image is available but the slave is offline (slave.IsLost).
  • Throws ObjectDisposedException when the Slave has been disposed (after Close()).
  • The guard checks liveness only at the moment the pointer is taken; callers that hold the pointer across cycles must re-check with slave.IsLost / slave.ProcessImageGeneration.

Example:

IntPtr p = slave.InputsPtr;
Console.WriteLine($"输入映像 {slave.InputsByteCount} 字节, 首地址 0x{p.ToInt64():X}"); // Input image {slave.InputsByteCount} bytes, start address 0x{p.ToInt64():X}

TryGetInputsPtr(out IntPtr pointer, out int byteCount)​

public bool TryGetInputsPtr(out IntPtr pointer, out int byteCount)

The non-throwing variant of InputsPtr, for callers such as real-time callbacks that must route a dropped slave through their own failure branch instead of throwing.

Parameters:

  • pointer (out IntPtr) — start address of the input process image; IntPtr.Zero when the method returns false
  • byteCount (out int) — size of the input process image in bytes; 0 when the method returns false

Return value:

  • bool — true = the pointer is usable and the data is not stale; false = the image is unavailable (not mapped / OP not entered) or the slave is offline

Description:

  • When it returns true, pointer is byte-for-byte the same as InputsPtr.
  • false does not distinguish "not mapped" from "offline"; to tell them apart, check slave.InputsByteCount and slave.IsLost.
  • Throws ObjectDisposedException when the Slave has been disposed (after Close()).
  • Input direction only: slave.OutputsPtr is the master's own shadow frame, whose validity does not depend on the slave being online.

Example:

if (slave.TryGetInputsPtr(out IntPtr ptr, out int len))
{
// usable this cycle: ptr is valid for len bytes
}
else if (slave.IsLost)
{
// slave offline: the image holds the last frame from before the drop
}

PdoInputStaleException​

public sealed class PdoInputStaleException : InvalidOperationException
{
public ushort MasterNumber { get; }
public ushort SlaveNumber { get; }
}

Thrown by InputsPtr / InputsMapping<T>() / InputsSliceMapping<T>(int) when the input image is available but the slave is offline: the image then holds the last frame from before the drop, not the current value.

Properties:

  • MasterNumber (ushort) — master instance number, the same value as master.MasterNumber
  • SlaveNumber (ushort) — slave index, the same value as slave.SlaveNum

Description:

  • The only liveness criterion is slave.IsLost: only a measured offline verdict counts as stale; with no measurement it reports online, so "not sampled" never becomes a false drop alarm on a healthy cycle.
  • Input direction only: the output area is the master's own shadow frame and stays valid while the slave is offline (the same criterion applies to the input direction only).
  • Derives from InvalidOperationException, so existing code that catches "PDO input image unavailable" with catch (InvalidOperationException) keeps working unchanged.
  • To check ahead of time instead of catching: use slave.IsLost or TryGetInputsPtr.
  • To take a snapshot and see staleness in the return value: use slave.CopyInputPdo(...), which reports PdoIoStatus.Stale.
Entry pointImage unavailableSlave offline
slave.InputsPtrInvalidOperationExceptionPdoInputStaleException
slave.PDO.InputsMapping<T>()InvalidOperationExceptionPdoInputStaleException
slave.PDO.InputsSliceMapping<T>(int offset)InvalidOperationException / ArgumentOutOfRangeExceptionPdoInputStaleException
slave.TryGetInputsPtr(...)returns falsereturns false
slave.GetInputDataSpan()empty spanempty span
slave.CopyInputPdo(...)a PdoIoStatus other than SuccessPdoIoStatus.Stale

Example:

try
{
ref readonly InPdo input = ref slave.PDO.InputsMapping<InPdo>();
Console.WriteLine($"pos={input.ActualPosition}");
}
catch (PdoInputStaleException ex)
{
Console.WriteLine($"主站 {ex.MasterNumber} 从站 {ex.SlaveNumber} 离线, 本拍输入不可用"); // Master {ex.MasterNumber} slave {ex.SlaveNumber} offline, this cycle's inputs are unavailable
}
note

A generation change and an offline slave are two different things: after a generation change, old refs and old pointers are invalid as a whole (map again when re-entering OP), whereas an offline slave keeps the image but marks it stale. Check both.

Direct access (works without mapping)​

The calls below are independent of struct mapping: they work without mapping, and are often used alongside it (to decode fields the struct cannot hold).

In[i] / Out[i]​

public PDOArrayInstance In  { get; }   // TxPDO (slave → master): read-only
public PDOArrayInstance Out { get; } // RxPDO (master → slave): read/write

Indexes process data elements by byte offset: In[i] reads inputs, Out[i] reads and writes outputs, and i is relative to the start of the process image for that direction.

Return value:

  • PDOArrayInstance — byte-indexed view of the process image; Length is the byte count of the process image for this direction, and 0 before OP is entered or before anything is mapped (any index then throws IndexOutOfRangeException)

Description:

  • In is the TxPDO, overwritten by the master every cycle, and read-only: assigning to In or writing one of its element members always throws InvalidOperationException.
  • Out is the RxPDO; each member assignment runs one versioned transaction (copy → patch → commit, with bounded retry on conflict), and a successful write is sent in the next cycle.
  • Throws InvalidOperationException when the commit fails.
  • Each element-view read takes a snapshot of the current frame and then resolves by offset — the same snapshot semantics as slave.PDO.Inputs, not the zero-copy pinned reference of InputsMapping<T>().
  • An out-of-range index throws IndexOutOfRangeException.
  • Out-of-range caused by a wrong byte / wrong type runs through two checks, with different exception types:
    • The first check tests against the element view's bounds (the Length captured at creation, that is, the direction byte count with about 50 ms of throttling): offset plus width past the end throws ArgumentOutOfRangeException — deliberately distinct from an index error, so a wrong byte is distinguishable from a wrong type.
    • The second check tests against the frame length actually obtained for this call (the snapshot read, or the frame leased by the write transaction): a mismatch with the element bounds throws ArgumentException. Only reachable once the element bounds are stale, or after a generation change shrinks the process image.
  • GetBit / SetBit throw when bitIndex is outside 0-7, and AsValue / WriteValue throw when the type is unsupported — ArgumentOutOfRangeException in both cases.
  • SetBit checks the direction before the index: a call on In throws InvalidOperationException whatever the index; only the Out direction can throw ArgumentOutOfRangeException for an out-of-range bitIndex.
  • Throws ObjectDisposedException when the Slave has been disposed.

Related structures:

public sealed class PDODataItem        // element view returned by slave.PDO.In[i] / Out[i]
{
public byte Content { get; set; } // raw byte (unsigned 8-bit)
public sbyte AsInt8 { get; set; } // signed 8-bit
public byte AsUInt8 { get; set; } // same byte with the same meaning as Content
public short AsInt16 { get; set; } // multi-byte members below are little-endian (EtherCAT wire order)
public ushort AsUInt16 { get; set; }
public int AsInt32 { get; set; }
public uint AsUInt32 { get; set; }
public long AsInt64 { get; set; }
public ulong AsUInt64 { get; set; }
public float AsFloat { get; set; }
public double AsDouble { get; set; }
public bool AsBool { get; set; } // bit0 read semantics; writes the whole byte as 1 / 0 (does not change a single bit)

public bool GetBit(int bitIndex); // bitIndex 0-7, 0 = LSB
public void SetBit(int bitIndex, bool value); // Out only; other bits in the same byte stay unchanged
public object AsValue(EcDataType type); // read a boxed value by mapping type
public void WriteValue(EcDataType type, object value); // write by mapping type
public static implicit operator byte(PDODataItem item); // byte x = slave.PDO.In[0]; ≡ .Content
}

AsBool reads only the lowest bit: both 0x02 and 0x80 read false. To judge truth by the whole byte being 0 or a value other than 0, read Content and compare it yourself.

Conversely, a bool field in the zero-copy ref mapping is true whenever the value is other than 0. For the same non-canonical byte, the ref mapping field and AsBool disagree; the ValueSnapshot snapshot is already normalized by bit0, so both agree.

GetBit(i) / SetBit(i, value) are the bitwise entry points for the same byte: i runs from 0 to 7, 0 = lowest bit; GetBit reads that bit (In / Out are both readable), and SetBit changes only that bit, leaving the other bits of the byte untouched.

The AsBool setter writes the whole byte

slave.PDO.Out[i].AsBool = value writes the whole byte as 1 or 0; it does not change only bit0 — slave.PDO.Out[0].AsBool = true also clears bits 1-7 of the same byte. When one byte carries both a boolean bit and other flag bits, use SetBit(i, value): it overwrites only the target bit and leaves the rest unchanged.

AsValue / WriteValue support only data types that map one-to-one to a CLR fixed-width type: Boolean, Integer8/16/32/64, Unsigned8/16/32/64, Real32/Real64.

Bit strings, 24/40/48/56-bit integers, strings and Domain all throw ArgumentOutOfRangeException. Use the public byte path for these wide types and bit strings: read the whole frame from the slave.PDO.Inputs / Outputs byte snapshots and slice by offset yourself, write several segments with TryWriteOutputBatch + PdoOutputPatch, and keep using AsValue / WriteValue for fixed-width scalars. 40/48/56-bit integers have no CLR scalar counterpart, so assemble and decode them byte by byte.

Example:

short sw = slave.PDO.In[0].AsInt16;        // read: current cycle
slave.PDO.Out[2].AsInt16 = 123; // write: versioned partial commit, sent in the next cycle
slave.PDO.Out[0].SetBit(0, true); // sets only bit0, other bits in the byte untouched
bool flag = slave.PDO.In[3].AsBool; // bit0 semantics
for (int i = 0; i < slave.PDO.Out.Length; i++)
slave.PDO.Out[i].SetBit(0, false); // walk the whole output image
byte same = slave.PDO.In[0]; // implicit conversion: same as .Content

TryWriteOutputBatch(patches)​

public bool TryWriteOutputBatch(IReadOnlyList<PdoOutputPatch> patches)

Commits several output byte segments in one versioned transaction: a successful call produces exactly one commit. Use it when several fields must be updated together instead of assigning Out[i].X = ... one by one (which is one transaction per field).

Parameters:

  • patches (IReadOnlyList<PdoOutputPatch>) — byte segments to commit; offsets are relative to the start of the output process image

Return value:

  • bool — whether the commit succeeded; false means the retry budget was exhausted (conflict / busy) and this call wrote nothing

Related structures:

public readonly struct PdoOutputPatch
{
public PdoOutputPatch(int offset, ReadOnlyMemory<byte> data); // a negative offset throws ArgumentOutOfRangeException
public int Offset { get; } // byte offset from the start of this slave's output process image
public ReadOnlyMemory<byte> Data { get; } // bytes to write for this segment
}

Description:

  • Before committing, each segment is copied into its own buffer, so retries are unaffected by later changes on the caller side.
  • A null patches throws ArgumentNullException; an empty Data segment, or an out-of-range offset / length, throws ArgumentException.
  • An empty list returns true.
  • The same method also exists on slave (slave.TryWriteOutputBatch) with identical semantics.

Example:

var patches = new[]
{
new PdoOutputPatch(0, new byte[] { 0x0F, 0x00 }), // ControlWord
new PdoOutputPatch(2, BitConverter.GetBytes(10000)), // TargetPosition
};
bool ok = slave.PDO.TryWriteOutputBatch(patches); // one transaction, one commit

Inputs / Outputs​

Byte-level access to the whole process image frame, for fields the struct cannot hold (strings, variable-length data).

public byte[] Inputs  { get; }        // whole input frame: every access returns a snapshot owned by the caller
public byte[] Outputs { get; set; } // whole output frame: get returns a snapshot; set commits the complete frame

Return value:

  • byte[] — a snapshot, not zero-copy: consistent within one cycle, and it does not follow the bus once copied out

Description:

  • These two properties are declared on slave.PDO (slave.PDO.Inputs), not on slave.
  • Every access allocates a new byte[]; in high-frequency loops use slave.CopyInputPdo(span, out copied, out required) / slave.CopyOutputPdo(...) to copy into your own buffer (no extra allocation, returns PdoIoStatus: only Success counts as success, and BufferTooSmall reports the required frame length).
  • Commit a whole frame with slave.WriteOutputPdo(span, out _, out _).
  • The convenience extensions slave.CopyInputsTo(Span<byte>) / slave.CopyToOutputs(ReadOnlySpan<byte>) return the number of bytes actually copied / written; a return of 0 means no complete frame was read or written this time (failure / BUSY / size mismatch), not "a normal result of 0 bytes". The specific cause is logged as a Warning (including status / copied / required / slave index).
  • The Outputs setter length must match OutputsByteCount, otherwise it throws InvalidOperationException.
  • Both getters throw ObjectDisposedException once the Slave has been disposed (after Close()).
  • Throws InvalidOperationException when a complete frame cannot be obtained (it does not return an empty array).

Example:

byte[] frame = slave.PDO.Inputs;
string name = System.Text.Encoding.ASCII.GetString(frame, 6, 16).TrimEnd('\0');

PdoConsistentReader​

public sealed class PdoConsistentReader
{
public PdoConsistentReader(ushort masterIndex); // number of the master this slave belongs to
public ulong CycleCount { get; } // number of completed cycles (increments by 1 each cycle)
public T Read<T>(Func<ulong, T> reader, int maxRetries = 8);
public T ReadInput<T>(Slave slave, int offset, int maxRetries = 8) where T : struct;
public int ReadInt32(Slave slave, int offset, int maxRetries = 8);
public short ReadInt16(Slave slave, int offset, int maxRetries = 8);
public byte ReadByte(Slave slave, int offset, int maxRetries = 8);
}

Use it when reading several fields as one logical frame: take the cycle number before and after the read, and the cycle counts as one complete read only when both match; any crossing of a cycle retries the whole thing. For a single field, In[i] is enough.

Description:

  • Consistency is detected by bracketing with the cycle number, and what you read is a snapshot of the current value; nothing is pinned and no raw pointer is returned.
  • Compared with taking slave.PDO.Inputs every time, it allocates no whole-frame array.
  • A slave that does not belong to the master bound at construction throws ArgumentException (a null slave throws ArgumentNullException).
  • Throws InvalidOperationException when no consistent snapshot is obtained after maxRetries attempts (8 by default): shorten the reading lambda or read fewer fields at once.
  • The legacy overloads that take an IntPtr are obsolete and throw NotSupportedException when called — a PDO pointer cannot stay valid across a generation change.

Example:

var reader = new PdoConsistentReader(masterIndex: 1);   // number of the master this slave belongs to

InPdo frame = reader.Read(_ => new InPdo
{
StatusWord = slave.PDO.In[0].AsUInt16,
ActualPosition = slave.PDO.In[2].AsInt32,
}); // both fields come from the same cycle, or the whole read is retried

Process image spans and direct buffer access​

These calls are the low-level entry points for moving whole frames. They are independent of struct mapping and of the In[i] / Out[i] element views: they work without mapping, and can be used alongside mapping to handle fields the struct cannot hold.

GetInputDataSpan()​

public ReadOnlySpan<byte> GetInputDataSpan()

A read-only span over the input process image that points at the process image itself (zero-copy, not a snapshot): reads always see the current cycle. The input direction is overwritten by the master every cycle, so writes through it are silently ignored.

When the process image is unavailable (OP not entered / nothing mapped / could not be obtained) it returns an empty span (Length == 0) instead of throwing; once the Slave has been disposed (after Close()) it throws ObjectDisposedException.

How it differs from slave.PDO.Inputs: the span allocates nothing and follows the current cycle; Inputs returns a snapshot owned by the caller on every access.

Return value:

  • ReadOnlySpan<byte> — view of the input process image; an empty span when unavailable

Example:

ReadOnlySpan<byte> input = slave.GetInputDataSpan();
if (input.Length < 2)
Console.WriteLine("输入映像不可用或不足 2 字节(未进 OP / 未映射)"); // Input image unavailable or fewer than 2 bytes (not in OP / not mapped)
else
Console.WriteLine($"StatusWord=0x{System.Buffers.Binary.BinaryPrimitives.ReadUInt16LittleEndian(input):X4}");

GetOutputDataSpan()​

public Span<byte> GetOutputDataSpan()

A writable span over the output process image that points at the process image itself (zero-copy): changing a byte changes the output sent in the next cycle. It returns an empty span when the process image is unavailable, and throws ObjectDisposedException once the Slave has been disposed.

Changing half a frame byte by byte leaves intermediate states that other readers can see. To make several segments take effect together, use TryWriteOutputBatch; to land a change only if nobody else modified the snapshot, use a versioned transaction (CopyOutputPdoVersioned / CommitOutputPdoVersioned).

Return value:

  • Span<byte> — view of the output process image; an empty span when unavailable

Example:

Span<byte> output = slave.GetOutputDataSpan();
if (output.Length >= 2)
{
output[0] = 0x0F; // ControlWord low byte
output[1] = 0x00;
}

ReadInputDataToSpan(Span<byte> destination)​

public int ReadInputDataToSpan(Span<byte> destination)

Copies the current input frame into the caller's span and returns the number of bytes actually copied. When the destination is longer than the frame, the whole frame is copied; when it is shorter, only the destination length is written and nothing goes out of bounds.

It returns 0 when nothing could be read (OP not entered / no mapping / failure) or the destination is empty — 0 means nothing was read this time, not "the frame length is 0".

Parameters:

  • destination (Span<byte>) — destination buffer

Return value:

  • int — number of bytes actually copied; 0 on failure

Example:

Span<byte> buffer = stackalloc byte[64];
int n = slave.ReadInputDataToSpan(buffer);
if (n == 0)
Console.WriteLine("读取失败或无输入映射"); // Read failed or no input mapping
else
Console.WriteLine($"读到 {n} 字节"); // Read {n} bytes

WriteOutputDataFromSpan(ReadOnlySpan<byte> source)​

public int WriteOutputDataFromSpan(ReadOnlySpan<byte> source)

Writes the source span into the output process image and returns the number of bytes actually written. When the length equals the output mapping, the whole frame is committed; a short frame performs a partial update against the output mapping (only the supplied segment is overwritten, the other bytes keep their previous values).

It returns 0 when source is empty or the write fails (no exception is thrown). WriteOutputPdo remains the single entry point for writing a whole frame.

Parameters:

  • source (ReadOnlySpan<byte>) — byte segment to write

Return value:

  • int — number of bytes actually written; 0 on failure

Example:

Span<byte> outFrame = stackalloc byte[2];
System.Buffers.Binary.BinaryPrimitives.WriteUInt16LittleEndian(outFrame, 0x000F);
int n = slave.WriteOutputDataFromSpan(outFrame);
Console.WriteLine(n == 2 ? "控制字已提交" : "写入失败或被拒"); // Control word submitted / write failed or rejected

ReadInputDataDirect(byte[] buffer, int offset = 0, int count = 0)​

public int ReadInputDataDirect(byte[] buffer, int offset = 0, int count = 0)

Copies the input frame into the given range of the caller's array. count = 0 means from offset through the end of the array.

On invalid arguments (buffer is null, offset is out of range) or a failed read it returns 0 and does not throw — the return value is the only way to detect the failure.

Parameters:

  • buffer (byte[]) — destination array
  • offset (int) — start offset within the destination array, 0 by default
  • count (int) — number of bytes to read, 0 = through the end of the array

Return value:

  • int — number of bytes actually read; 0 on failure

Example:

byte[] frame = new byte[slave.InputsByteCount];
int n = slave.ReadInputDataDirect(frame);
if (n == 0)
Console.WriteLine("未读到输入帧"); // No input frame read

WriteOutputDataDirect(byte[] buffer, int offset = 0, int count = 0)​

public int WriteOutputDataDirect(byte[] buffer, int offset = 0, int count = 0)

Writes the given range of the array into the output process image. count = 0 means from offset through the end of the array.

On invalid arguments or a failed write it returns 0 and does not throw.

Parameters:

  • buffer (byte[]) — source array
  • offset (int) — start offset within the source array, 0 by default
  • count (int) — number of bytes to write, 0 = through the end of the array

Return value:

  • int — number of bytes actually written; 0 on failure

Example:

byte[] frame = new byte[slave.OutputsByteCount];
frame[0] = 0x0F;
int n = slave.WriteOutputDataDirect(frame);
Console.WriteLine(n > 0 ? $"已写入 {n} 字节" : "写入未被接受"); // Wrote {n} bytes / write not accepted

Versioned output transactions​

This group covers optimistic concurrent writing: take an output snapshot together with a version token bound to it, change fields on the snapshot, then commit only if nobody changed the output in the meantime. Use it when several writers (UI, scripts, cyclic tasks) write to the same slave at the same time, so they do not overwrite each other. A single regular writer should not take this path; using a mapping or Out[i] directly is cheaper.

CopyOutputPdoVersioned(...)​

public PdoIoStatus CopyOutputPdoVersioned(
Span<byte> destination, out int copiedSize, out int requiredSize,
ref ulong transactionTicket, ref ulong nativeDeadlineUs,
out ulong versionToken)

Copies the complete RxPDO and returns a version token bound exactly to that snapshot.

On the first call, transactionTicket and nativeDeadlineUs must both be 0; the SDK issues an opaque ticket and deadline pair. Every later retry after growing the buffer, every restart and every commit must reuse the same pair. The token must be passed to CommitOutputPdoVersioned unchanged.

Parameters:

  • destination (Span<byte>) — buffer that receives the current output snapshot; leave it empty to obtain just the required length
  • copiedSize (out int) — number of bytes actually copied
  • requiredSize (out int) — bytes required for the complete frame; grow the buffer to this size when BufferTooSmall
  • transactionTicket (ref ulong) — transaction ticket; pass 0 on the first call
  • nativeDeadlineUs (ref ulong) — transaction deadline in microseconds; pass 0 on the first call
  • versionToken (out ulong) — version token bound to this snapshot

Return value:

  • PdoIoStatus — Success the snapshot is valid; BufferTooSmall the buffer is too small (grow it to requiredSize and retry with the same ticket / deadline pair); Busy the transaction is busy (retry with the ticket / deadline unchanged); Conflict / Stale someone else changed the snapshot, copy it again; Failed failure (the ticket / deadline are reset to 0)

Example:

ulong ticket = 0, deadline = 0;
byte[] snapshot = new byte[slave.OutputsByteCount];

PdoIoStatus st = slave.CopyOutputPdoVersioned(
snapshot, out int copied, out int required,
ref ticket, ref deadline, out ulong token);

if (st == PdoIoStatus.Success)
{
snapshot[0] = 0x0F; // Modify fields on the snapshot
st = slave.CommitOutputPdoVersioned(
snapshot.AsSpan(0, copied), token, ticket, deadline,
out ulong committed, out int written, out int need);
}

CommitOutputPdoVersioned(...)​

public PdoIoStatus CommitOutputPdoVersioned(
ReadOnlySpan<byte> source, ulong expectedToken,
ulong transactionTicket, ulong nativeDeadlineUs,
out ulong committedToken, out int writtenSize, out int requiredSize)

Commits the modified output frame after validating the token: the change lands only if the output has not been modified by another writer since the snapshot was copied.

Parameters:

  • source (ReadOnlySpan<byte>) — byte segment to commit (usually the whole frame that was copied out)
  • expectedToken (ulong) — version token returned by CopyOutputPdoVersioned
  • transactionTicket (ulong) — the same transaction ticket used for the copy
  • nativeDeadlineUs (ulong) — the same deadline used for the copy
  • committedToken (out ulong) — new version token after the commit
  • writtenSize (out int) — number of bytes actually written (meaningful only on Success)
  • requiredSize (out int) — bytes required for the complete frame

Return value:

  • PdoIoStatus — Success committed; Busy the transaction is busy (retry with the same ticket / deadline pair); Conflict / Stale the snapshot was changed (copy the snapshot again); SizeMismatch the length does not match the output mapping; Failed failure

Example:

PdoIoStatus st = slave.CommitOutputPdoVersioned(
snapshot.AsSpan(0, copied), token, ticket, deadline,
out ulong committed, out int written, out int need);

if (st == PdoIoStatus.Conflict || st == PdoIoStatus.Stale)
Console.WriteLine("快照已被其他写入方改动,需重新复制后重试"); // Snapshot was changed by another writer, copy it again before retrying
else if (st == PdoIoStatus.Busy)
Console.WriteLine("事务忙,保持同一对票据重试"); // Transaction busy, retry with the same pair of tickets

PDO IO status normalization​

NormalizePdoIoStatus(byte status)​

public static PdoIoStatus NormalizePdoIoStatus(byte status)

Normalizes a status byte to PdoIoStatus, for decoding the raw status returned by entry points such as CopyInputPdo / WriteOutputPdo and the versioned transactions.

Mapping rules:

  • 0x00 and 1 → Success (both success encodings are accepted)
  • 2..6 → BufferTooSmall / SizeMismatch / Conflict / Stale / Busy
  • 0xFA..0xFF → the negative status codes encoded as bytes, mapped value by value back to Conflict / Stale / SizeMismatch / BufferTooSmall / Busy / Failed
  • any other value → Failed

The public status codes 2..6 match, value for value, the same-named normalization entry point in the other language SDKs. The method is hidden from IntelliSense by default and is meant for direct calls from tests and status decoding.

Parameters:

  • status (byte) — raw status byte

Return value:

  • PdoIoStatus — normalized status

Related structures:

public enum PdoIoStatus : byte
{
Failed = 0, // Failure (including an unrecognised status code)
Success = 1, // Success
BufferTooSmall = 2, // Buffer too small, grow it to requiredSize and retry
SizeMismatch = 3, // Length does not match the mapping
Conflict = 4, // Concurrent write conflict, re-take the snapshot and retry
Stale = 5, // The snapshot has expired
Busy = 6 // Transaction busy, retry later
}

Example:

byte rawStatus = 0xFD;   // For example the raw return from a whole-frame copy entry point
PdoIoStatus st = DarraEtherCAT.Slave.NormalizePdoIoStatus(rawStatus);
if (st == PdoIoStatus.BufferTooSmall)
Console.WriteLine("缓冲区不足,按所需长度扩容后重试"); // Buffer too small, expand it to the required length and retry