PDO inputs and outputs
Access the process image through the free functions of the darra::SlavePDO namespace; element views come from darra::PDOArrayInstance and are constructed by the caller as needed.
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 refresh; a read always sees the current cycle, and a write is sent in the next cycle.
- A single process image in this product (inputs + outputs + per-slave mailbox state combined) is capped at 64 KB (65536 bytes)
- Slave count: the slave table of each master is capped at 2048 (a 1-based table, so at most 2047 slaves)
- When sizing, plan so that each process data group stays as lean as possible; an oversized group loses the zero-copy fast path and falls back to multi-frame forwarding
Mailbox communication (SDO / CoE / FoE and so on) rides along with the PDO cycle automatically and does not consume an extra frame; a response takes about 2 PDO cycles.
Usage examples
Day-to-day usage
① Map to a struct (zero-copy, keep using it): after entering OP, map once to get a reference into the real-time process image, then read and write it like a variable.
#include "ethercat.hpp"
#include <cstdio>
#pragma pack(push, 1) // Must: the struct lines up byte for byte with the PDO mapping
struct InPdo { uint16_t statusWord; int32_t actualPosition; };
struct OutPdo { uint16_t controlWord; int32_t targetPosition; };
#pragma pack(pop)
int main() {
dll_t dll;
darra::EtherCATMaster master(dll);
master.SetENI("C:\\EtherCAT\\MyProject.deni"); // DENI one-line load
if (!master.Build() || !master.SetState(darra::EcState::OP)) return 1;
const uint16_t mi = master.MasterNumber();
const uint16_t si = 1; // Slave index, 1-based
const InPdo& in = darra::SlavePDO::InputsMapping<InPdo>(dll, mi, si);
OutPdo& out = darra::SlavePDO::OutputsMapping<OutPdo>(dll, mi, si);
out.controlWord = 0x000F; // Write: sent next cycle
out.targetPosition = 10000;
std::printf("status=0x%04X pos=%d\n",
static_cast<unsigned>(in.statusWord), in.actualPosition);
}
② Single read (one-off): no struct; take one set of current values only.
// Single point: read one typed value by byte offset, returns std::nullopt on failure
if (auto sw = darra::SlavePDO::ReadUInt16(dll, mi, si, 0))
std::printf("status=0x%04X\n", static_cast<unsigned>(*sw));
if (auto name = darra::SlavePDO::ReadString(dll, mi, si, 6, 16))
std::printf("name=%s\n", name->c_str());
// Whole frame: a complete input frame snapshot, one generation, copied out it does not follow the bus
std::vector<uint8_t> frame;
if (darra::SlavePDO::CopyInputFrame(dll, mi, si, frame) && frame.size() >= 2)
std::printf("快照 %zu 字节, status=0x%04X\n", frame.size(), // Snapshot %zu bytes, status=0x%04X\n
static_cast<unsigned>(frame[0] | (frame[1] << 8)));
Cyclic changes
One mapping is enough; put the same mapping straight into your own cycle loop and use it directly:
while (running) {
out.controlWord = (in.statusWord & 0x0004) ? static_cast<uint16_t>(0x000F)
: static_cast<uint16_t>(0x0006);
out.targetPosition = in.actualPosition;
WaitNextTick(); // Your own pacing, e.g. 1 ms
}
The master moves process data every cycle: what you read in the loop is always the current cycle, what you write is sent in the next cycle, no extra call is needed, and do not re-map on every tick (the reference only becomes invalid after the master is rebuilt / re-enters OP; when you re-enter OP, take it once more).
Freshness model
Read interfaces fall into two kinds; you must know the difference before mixing them:
- live reference: the references returned by
InputsMapping<T>()/OutputsMapping<T>()/InputsSliceMapping<T>()point straight at the process image; there is no "read once" action. - snapshot: the element accessors and the
Read*family take a fresh complete PDO frame for the current direction on every call, then decode it by offset.- The partial-write members of the
Write*family take a complete frame on every call, modify it, then submit the whole frame as a versioned commit:WriteInt8…WriteDouble,WriteString, element accessor setters,PatchOutputFrame()/MutateOutputFrame()
WriteOutputFrame()is an unconditional whole-frame replacement.
- The partial-write members of the
When a real-time callback must do "take the input pointer + test whether this slave is online" inside one tick and cannot throw, use Slave::TryGetInputsPtr() (see the Slave::TryGetInputsPtr() section on this page): std::nullopt means the input value must not be consumed this tick, and the staleness test is the same one the snapshot path uses (its single source of truth is IsLost()).
So an element accessor or a Read* call is "one call =
one new complete snapshot", and two calls in the same expression may land on two different bus cycles:
// Two calls = two independent snapshots, not guaranteed to be the same tick
int32_t delta = darra::SlavePDO::ReadInt32(dll, mi, si, 6).value_or(0)
- darra::SlavePDO::ReadInt32(dll, mi, si, 2).value_or(0);
When several fields must be consistent, pick one of these:
① Copy the mapped reference by value (the mapping is zero-copy; the copy no longer follows the bus):
const InPdo& live = darra::SlavePDO::InputsMapping<InPdo>(dll, mi, si);
InPdo snapshot = live; // All fields come from the same copy
int32_t pos = snapshot.actualPosition;
② Whole-frame snapshot: take one complete frame, then decode it by offset yourself.
std::vector<uint8_t> frame;
if (darra::SlavePDO::CopyInputFrame(dll, mi, si, frame) && frame.size() >= 2)
std::printf("status=0x%04X\n", // The fields in the frame come from the same snapshot
static_cast<unsigned>(frame[0] | (frame[1] << 8)));
③ Whole-frame read into your own buffer: ReadInputDirect() fills the caller's buffer in one call; when the buffer is too small it does not copy half a frame.
uint8_t buf[64];
int n = darra::SlavePDO::ReadInputDirect(dll, mi, si, buf, sizeof(buf)); // 0 = failure
std::printf("读到 %d 字节\n", n); // Read %d bytes\n
The zero-copy path is this family:
InputsMapping<T>(),OutputsMapping<T>(),InputsSliceMapping<T>(),OutputsSliceMapping<T>()InputsSliceMapping(offset, size)/OutputsSliceMapping(offset, size)(returns a live byte slice)InputDataPointer(),OutputDataPointer()
The element accessors and the Read* family take a whole-frame snapshot every call.
The partial writes in Write* use versioned commits, and WriteOutputFrame() is an unconditional whole-frame replacement — neither is a zero-copy path.
For the input direction, Slave::TryGetInputsPtr() is the guarded single call: it returns the same address as InputDataPointer() together with the input byte count, and yields std::nullopt once the slave is offline, so the caller never consumes the last frame left behind by a dropout (see TryGetInputsPtr()).
Struct mapping (zero-copy)
The mapping entry points overlay a live process image as a reference (not a snapshot): map once, then keep reading the same reference.
dll comes from master.Dll(), mi from master.MasterNumber(), and si is the 1-based slave index.
Failures are fail-closed and throw std::runtime_error:
- An unavailable image throws
std::runtime_error(separate messages for the input and output image):"PDO 输入映像不可用"(SDK output, = input PDO image unavailable) /"PDO 输出映像不可用"(SDK output, = output PDO image unavailable). - A
sizeof(T)that exceeds the size throwsstd::runtime_error(separate messages for the input and output PDO):"结构体大于输入 PDO"(SDK output, = struct larger than input PDO) /"结构体大于输出 PDO"(SDK output, = struct larger than output PDO).
#pragma pack(push, 1)(or#pragma pack(1)) is mandatory, and the field order must match the PDO mapping byte for byte; omitting pack still compiles, but the struct then carries alignment padding and every field is misaligned.sizeof(T)must not exceed the byte count for that direction (slave.Ibytes()/slave.Obytes()), otherwise it throws; exact equality is not required, smaller is legal.Tmust be trivially copyable and standard layout, which is a compile-timestatic_assert; a type with virtual functions / reference members / non-trivial copy overlays onto the process image incorrectly.- The input side is read-only — writing it is silently ineffective. To write process data, use the output-direction mapping.
- A mapping stays valid within the current generation of the master's process image; after the master is rebuilt / re-enters OP it must be mapped again.
InputsMapping<T>()
namespace darra::SlavePDO {
template<typename T>
const T& InputsMapping(dll_t& dll, uint16_t mi, uint16_t si);
}
Maps the input process image (TxPDO) to a read-only struct reference; after one mapping, reading a field reads the current cycle value.
Parameters:
dll(dll_t&) — DLL contextmi(uint16_t) — master indexsi(uint16_t) — slave index (1-based)
Return value:
const T&— read-only reference into the real-time process image
Example:
#pragma pack(push, 1)
struct InPdo { uint16_t statusWord; int32_t actualPosition; };
#pragma pack(pop)
const InPdo& in = darra::SlavePDO::InputsMapping<InPdo>(dll, mi, 1);
uint16_t sw = in.statusWord; // Current cycle value
OutputsMapping<T>()
namespace darra::SlavePDO {
template<typename T>
T& OutputsMapping(dll_t& dll, uint16_t mi, uint16_t si);
}
Maps the output process image (RxPDO) to a struct reference; writing a field writes it back to the process image.
Parameters:
dll(dll_t&) — DLL contextmi(uint16_t) — master indexsi(uint16_t) — slave index (1-based)
Return value:
T&— writable reference pointing straight at the real-time process image; a field written is sent to the slave in the next cycle
Example:
#pragma pack(push, 1)
struct OutPdo { uint16_t controlWord; int32_t targetPosition; };
#pragma pack(pop)
OutPdo& out = darra::SlavePDO::OutputsMapping<OutPdo>(dll, mi, 1);
out.controlWord = 0x000F; // Sent next cycle
InputsSliceMapping<T>() / OutputsSliceMapping<T>()
namespace darra::SlavePDO {
template<typename T>
const T& InputsSliceMapping(dll_t& dll, uint16_t mi, uint16_t si, int offset);
template<typename T>
T& OutputsSliceMapping(dll_t& dll, uint16_t mi, uint16_t si, int offset);
}
Overlays a struct reference at the given byte offset of the process image, for modular devices that split the image by module. Writing a field on the output side writes it back to the process image.
Parameters:
dll(dll_t&) — DLL contextmi(uint16_t) — master indexsi(uint16_t) — slave index (1-based)offset(int) — byte offset relative to the start of this slave's process image for this direction
Return value:
const T&/T&— reference at that offset (zero-copy)
Description: an unavailable image throws std::runtime_error; offset < 0 or offset + sizeof(T) beyond the end throws
std::out_of_range.
Example:
#pragma pack(push, 1)
struct Module1In { uint16_t status; };
struct Module2In { int32_t position; };
#pragma pack(pop)
// Module 1 starts at offset 0, module 2 at offset 8
const Module1In& m1 = darra::SlavePDO::InputsSliceMapping<Module1In>(dll, mi, 1, 0);
const Module2In& m2 = darra::SlavePDO::InputsSliceMapping<Module2In>(dll, mi, 1, 8);
InputsSliceMapping(int offset, int size) / OutputsSliceMapping(int offset, int size)
namespace darra::SlavePDO {
std::pair<const uint8_t*, int> InputsSliceMapping(dll_t& dll, uint16_t mi,
uint16_t si, int offset, int size);
std::pair<uint8_t*, int> OutputsSliceMapping(dll_t& dll, uint16_t mi,
uint16_t si, int offset, int size);
}
Takes a live process image slice by bytes, for variable-length fields that do not fit a struct.
{nullptr, 0} means out of range (offset < 0, size <= 0, offset + size
beyond the byte count of this direction) or the image is unavailable; a pointer outside the image is never returned.
Parameters:
dll(dll_t&) — DLL contextmi(uint16_t) — master indexsi(uint16_t) — slave index (1-based)offset(int) — byte offsetsize(int) — slice length in bytes
Return value:
std::pair<const uint8_t*, int>/std::pair<uint8_t*, int>—(指针, 字节数); the input direction is read-only, the output direction writes through to the process image
Example:
auto outSlice = darra::SlavePDO::OutputsSliceMapping(dll, mi, 1, 4, 8);
if (outSlice.first)
outSlice.first[0] = 0x01; // Write back to the process image, sent next cycle
InputDataPointer() / OutputDataPointer()
namespace darra::SlavePDO {
void* InputDataPointer(dll_t& dll, uint16_t mi, uint16_t si);
void* OutputDataPointer(dll_t& dll, uint16_t mi, uint16_t si);
}
Takes a raw pointer into the live process image (TxPDO / RxPDO). Returns nullptr on failure; the pointer stays valid while the master is running. The input side is read-only
— writing it is silently ineffective.
Parameters:
dll(dll_t&) — DLL contextmi(uint16_t) — master indexsi(uint16_t) — slave index (1-based)
Return value:
void*— pointer to the start of the process image;nullptr= could not be obtained
Example:
auto* inBytes = static_cast<const uint8_t*>(darra::SlavePDO::InputDataPointer(dll, mi, 1));
auto* outBytes = static_cast<uint8_t*>(darra::SlavePDO::OutputDataPointer(dll, mi, 1));
TryGetInputsPtr()
std::optional<std::pair<const void*, int>> Slave::TryGetInputsPtr() const;
Gets the input image pointer and checks whether the slave is online in one call, and never throws. It is a member of Slave (master.GetSlave(1).TryGetInputsPtr()), not a darra::SlavePDO free function: the mapping entries such as InputsMapping<T>() throw PdoInputStaleException on a stale frame, which a real-time callback cannot afford.
Return value:
std::optional<std::pair<const void*, int>>— on success{输入映像首地址, 输入字节数}, the same addressInputDataPointer()returnsstd::nullopt— the input value must not be used this time
Cases that return std::nullopt:
- GetIO unavailable (no mapping / not in OP)
- the pointer is null
- the byte count is
<= 0 IsLost()is true (the slave is offline)
Description:
- While a slave is offline the input area still holds the last frame before the dropout, which is not the current value and must never be consumed as live data. The staleness test uses the same criterion as the snapshot path, and its single source of truth is
IsLost(): only a measured LOST verdict blocks the read — "not measured" is not treated as offline and does not fail a healthy cycle. - The guard applies to the input direction only. The output area is the master's own shadow frame, so a slave going offline does not invalidate it, and output access is not stale-guarded.
- The guard holds only at the instant the pointer is taken. A caller that caches the pointer across cycles must re-check
IsLost()itself; the pointer stays valid until the master is closed or the process image generation changes.
Example:
auto& slave = master.GetSlave(1);
// In the real-time callback: take the pointer and test online in one go; no exception is thrown on failure
if (auto in = slave.TryGetInputsPtr()) {
const auto* bytes = static_cast<const uint8_t*>(in->first);
const int size = in->second;
if (size >= 2) {
uint16_t status = static_cast<uint16_t>(bytes[0] | (bytes[1] << 8));
// ... use this cycle's input values
}
} else {
// Lost slave / not in the mapping / not in OP: the input value must not be consumed this cycle, take your own failure branch
}
InputDataSize() / OutputDataSize()
namespace darra::SlavePDO {
int InputDataSize(dll_t& dll, uint16_t mi, uint16_t si);
int OutputDataSize(dll_t& dll, uint16_t mi, uint16_t si);
}
The authoritative frame length of the process image for this direction (length lookup only, no data copy), used to check the struct size before mapping and to give element views their length.
Parameters:
dll(dll_t&) — DLL contextmi(uint16_t) — master indexsi(uint16_t) — slave index (1-based)
Return value:
int— byte count;0when the frame length cannot be read (image unavailable / probe failed). Do not read0as "empty frame" or as some particular state
Example:
const int inLen = darra::SlavePDO::InputDataSize(dll, mi, 1);
if (inLen < static_cast<int>(sizeof(InPdo)))
std::printf("结构体大于输入 PDO\n"); // (SDK output, = struct larger than input PDO)
Direct access (element views)
You can read and write a single element by byte offset without mapping a struct. The array view is darra::PDOArrayInstance, constructed by the caller directly from a
dll_t, the master index, the slave index and the byte count for this direction.
If you do not want to create a darra::PDOArrayInstance, you can also use the C element functions shipped in include/slave/pdo.h:
build an array view over a frame, take an element by offset, read and write values by type. These functions are inline implementations in the C header; C++ can call them after including
ethercat.hpp, and the C++ header does not define them again; for the exact signatures and size conventions see
the element view section of the C SDK PDO page.
The element view is not attached to the slave object; build one darra::PDOArrayInstance per direction: take the length from that direction's
darra::SlavePDO::InputDataSize(dll, mi, si) /
darra::SlavePDO::OutputDataSize(dll, mi, si), and pass is_input as true / false to select the direction.
darra::ethercat::SlavePdoAccess is the older wrapper around this page's family of free functions (Inputs() / Outputs()
/ SetOutputs() / InputArray() / OutputArray()); it is kept only for compatibility with existing code and new code does not need it. Its
WriteOutputDataDirect() is marked deprecated and always returns 0; it is permanently fail-closed.
PDOArrayInstance
namespace darra {
class PDOArrayInstance {
public:
PDOArrayInstance(dll_t& dll, uint16_t mi, uint16_t si,
int length, bool is_input);
PDODataItem operator[](int index) const; // Get an element view by byte offset
int Length() const; // Process image byte count for this direction
};
}
Indexes process data elements by byte offset: index is relative to the start of the process image for this direction, and an out-of-range index throws
std::out_of_range("索引超出范围"). Elements are wrapped as PDODataItem by offset, returned by value, with no heap allocation.
The other constructor overload PDOArrayInstance(uint8_t* data_ptr, int length, bool is_input)
accepts the caller's own buffer base address; elements read and write that memory directly by offset and bypass snapshots and versioned commits.
Parameters:
dll(dll_t&) — DLL contextmi(uint16_t) — master indexsi(uint16_t) — slave index (1-based)length(int) — byte count of the process image for this direction, fromInputDataSize()/OutputDataSize()is_input(bool) —truefor the input direction (TxPDO, read-only),falsefor the output direction (RxPDO)
Related structure:
class PDODataItem { // An element is a view, not a copy: it only stores base/index/offset/direction
public:
// Byte
uint8_t Content() const; void Content(uint8_t value);
// Fixed-width scalars: use the parameterless overload to read and the single-parameter overload of the same name to write; multi-byte values are always little-endian (this SDK never swaps bytes)
int8_t AsInt8() const; void AsInt8(int8_t value);
uint8_t AsUInt8() const; void AsUInt8(uint8_t value); // Same meaning and same bytes as Content
int16_t AsInt16() const; void AsInt16(int16_t value);
uint16_t AsUInt16() const; void AsUInt16(uint16_t value);
int32_t AsInt32() const; void AsInt32(int32_t value);
uint32_t AsUInt32() const; void AsUInt32(uint32_t value);
int64_t AsInt64() const; void AsInt64(int64_t value);
uint64_t AsUInt64() const; void AsUInt64(uint64_t value);
float AsFloat() const; void AsFloat(float value);
double AsDouble() const; void AsDouble(double value);
// Boolean: bit0 semantics
bool AsBool() const; void AsBool(bool value); // Write: whole byte 0 / 1
// Bit: index 0-7, 0 = LSB
bool GetBit(int bitIndex) const;
void SetBit(int bitIndex, bool value); // Leave the rest of the byte alone
// By mapping type
PDOValue AsValue(EcDataType type) const;
void WriteValue(EcDataType type, const PDOValue& value);
// Wide type outlet (bit strings / variable-length types)
BaseData AsBaseData(EcDataType type) const;
bool WriteFromBaseData(const BaseData& data);
operator uint8_t() const; // Implicit conversion, same as Content()
};
Example:
darra::PDOArrayInstance in (dll, mi, si, // Input element view (TxPDO)
darra::SlavePDO::InputDataSize(dll, mi, si), true);
darra::PDOArrayInstance out(dll, mi, si, // Output element view (RxPDO)
darra::SlavePDO::OutputDataSize(dll, mi, si), false);
if (in.Length() >= 4) {
int32_t pos = in[2].AsInt32(); // Read: 4 bytes from offset 2
std::printf("pos=%d\n", pos);
}
out[0].AsInt16(123); // Write: versioned local commit, sent next cycle
uint8_t raw = in[3]; // Implicit conversion: same as in[3].Content()
AsBool()
bool AsBool() const;
void AsBool(bool value);
Reads and writes a truth value as a whole byte, with bit0 semantics: it is true only when the lowest bit is 1.
Return value:
bool— the value of the lowest bit of the whole byte (0→false,1→true)
Description:
- The non-canonical bytes
0x02and0x80both readfalse— it is not "non-zero is true". - The SDK offers this one boolean convention only; to judge truth by whole-byte 0 / a value other than 0, read
Content()and compare yourself. - The write direction writes
1or0into the whole byte (not a single bit); for bit-level read and write useGetBit()/SetBit().
Example:
bool flag = in[3].AsBool(); // true only when the lowest bit is 1
uint8_t b = in[3].Content(); // Read the raw byte when you need to judge truth by whole byte 0 / a value other than 0
out[3].AsBool(true); // Write: the whole byte = 0x01
GetBit() / SetBit()
bool GetBit(int bitIndex) const;
void SetBit(int bitIndex, bool value);
Reads and writes one bit inside the byte the element sits on.
Parameters:
bitIndex(int) — bit index,0-7, where0is the least significant bit (LSB)value(bool) — the bit value to write
Return value:
bool— the value of that bit
Description:
- The bit index uses only the one byte at the element offset, regardless of the element width:
- On an
AsInt16/AsInt32element, indices0-7still access the starting byte only and never cross into following bytes.
- On an
- A bit index outside
0-7throwsstd::out_of_range. Message:std::out_of_range("位索引必须在 0-7 之间")(SDK output, = bit index must be within the valid range). SetBitthrowsstd::runtime_erroron the input direction (an input PDO cannot be written), messagestd::runtime_error("不能写入输入 PDO")(SDK output, = cannot write an input PDO); while writing, the other bits of the same byte stay untouched, and a failed commit throwsstd::runtime_error.- The equivalent entry points addressed by byte offset (instead of element offset) are:
darra::SlavePDO::GetBit(dll, mi, si, byteOffset, bitOffset)SetBit(dll, mi, si, byteOffset, bitOffset, value)- These are addressed by byte offset and differ slightly in semantics:
GetBitthrowsstd::out_of_rangewhen the byte cannot be read or the bit offset is out of range;SetBitthrowsstd::out_of_rangefor an out-of-range argument andstd::runtime_errorwhen the whole-frame commit fails.
Example:
bool b0 = in[3].GetBit(0); // bit0 of the byte at offset 3
out[3].SetBit(0, true); // Set bit0 only, leave the rest of the byte alone
AsValue() / WriteValue()
PDOValue AsValue(EcDataType type) const;
void WriteValue(EcDataType type, const PDOValue& value);
Reads and writes a scalar by EtherCAT data type: a read takes the value at the current position according to type, a write converts the value according to type and stores it at the current position.
Parameters:
type(EcDataType) — the mapping type at this position (from the PDO mapping entry in the ESI/ENI)value(const PDOValue&) — the value to write, converted according totype
Return value:
PDOValue— the scalar corresponding totype
Description:
- Only the 11 fixed-width types are accepted:
BOOLEAN,INTEGER8/16/32/64,UNSIGNED8/16/32/64,REAL32,REAL64. - Bit strings (
BIT1..BIT8),INTEGER24/40/48/56, strings andDOMAINall throwstd::out_of_range— no guessing the width, no silent 1-byte read. WriteValueconverts the value to the target type (float → integer rounds to nearest), and a value outside the target type range throwsstd::out_of_range.BOOLEANtakesboolas-is; other values are judged true/false by 0 / a value other than 0, then stored with the whole-byte bit0 semantics ofAsBool.
Related structure:
using PDOValue = std::variant<bool, int8_t, uint8_t, int16_t, uint16_t,
int32_t, uint32_t, int64_t, uint64_t,
float, double>;
Example:
darra::PDOValue v = in[2].AsValue(darra::EcDataType::INTEGER32);
if (auto p = std::get_if<int32_t>(&v))
std::printf("pos=%d\n", *p);
out[0].WriteValue(darra::EcDataType::INTEGER16, static_cast<int16_t>(-100));
AsBaseData() / WriteFromBaseData()
BaseData AsBaseData(EcDataType type) const;
bool WriteFromBaseData(const BaseData& data);
The exit for bit strings / variable-length types outside the 11 fixed-width types: raw bytes in and out through a BaseData wrapper.
Parameters:
type(EcDataType) — the mapping type at this position; the byte width comes from the data type table (ValueCodec::TypeBitSizerounded up to whole bytes), and a type whose width cannot be resolved is handled as 1 bytedata(const BaseData&) — the whole run of raw bytes to write back
Return value:
BaseData— a wrapper over the raw bytes copied out of the current position according to thetypewidthbool— whether the write succeeded; failure returnsfalse(no throw), and the input direction always returnsfalse
Description:
AsBaseDatathrowsstd::out_of_rangewhen out of range.- A frame snapshot that cannot be taken throws
std::runtime_error. Message:std::runtime_error("PDO 快照不可用")(SDK output, = frame snapshot unavailable). - A data type table that yields no valid width throws
std::invalid_argument. WriteFromBaseDatauses the versioned commit on the output direction; any failure is returned asfalse.
Example:
darra::ethercat::BaseData wide = in[0].AsBaseData(darra::EcDataType::BIT3); // Bit string
bool ok = out[0].WriteFromBaseData(wide); // Returns false on failure
Whole-frame snapshots and typed single points
CopyInputFrame() / CopyOutputFrame()
namespace darra::SlavePDO {
bool CopyInputFrame(dll_t& dll, uint16_t mi, uint16_t si,
std::vector<uint8_t>& frame);
bool CopyOutputFrame(dll_t& dll, uint16_t mi, uint16_t si,
std::vector<uint8_t>& frame);
}
Copies one complete PDO frame of the current generation into the caller's container; this is the SDK's whole-frame snapshot entry point.
Parameters:
dll(dll_t&) — DLL contextmi(uint16_t) — master indexsi(uint16_t) — slave index (1-based)frame(std::vector<uint8_t>&) — output parameter; it is cleared on failure and never leaves an old or partial frame behind
Return value:
bool— whether it succeeded;falsewhen the frame length exceeds the 64 KiB cap or the frame-fetch state is self-contradictory
Example:
std::vector<uint8_t> frame;
if (darra::SlavePDO::CopyInputFrame(dll, mi, 1, frame))
std::printf("%zu 字节\n", frame.size()); // %zu bytes\n
ReadInputDirect()
namespace darra::SlavePDO {
int ReadInputDirect(dll_t& dll, uint16_t mi, uint16_t si,
uint8_t* buffer, int bufferSize);
}
Reads the complete input frame into the caller's buffer in one call; when the buffer is too small it does not copy half a frame.
Parameters:
dll(dll_t&) — DLL contextmi(uint16_t) — master indexsi(uint16_t) — slave index (1-based)buffer(uint8_t*) — destination bufferbufferSize(int) — buffer capacity in bytes
Return value:
int— the number of bytes actually read; any failure (not in OP, buffer too small, null pointer) returns0
Example:
uint8_t buf[64];
int n = darra::SlavePDO::ReadInputDirect(dll, mi, 1, buf, sizeof(buf));
WriteOutputFrame() / PatchOutputFrame() / MutateOutputFrame()
namespace darra::SlavePDO {
enum class PdoIoStatus : uint8_t {
Failed = 0, // Failure
Ok = 1, // Success
BufferTooSmall = 2, // Buffer too small
SizeMismatch = 3, // Size mismatch
Conflict = 4, // Version conflict (the output was changed by someone else)
Stale = 5, // The data has expired
Busy = 6 // Busy (a retry later may succeed)
};
struct PdoWriteResult {
PdoIoStatus status; // Write status
uint32_t written; // Number of bytes actually written
uint32_t required; // Authoritative frame length
bool Succeeded(uint32_t requestedSize) const noexcept;
};
PdoWriteResult WriteOutputFrame(dll_t& dll, uint16_t mi, uint16_t si,
const uint8_t* data, uint32_t size);
bool PatchOutputFrame(dll_t& dll, uint16_t mi, uint16_t si,
size_t offset, const void* data, size_t size);
template<typename Mutator>
bool MutateOutputFrame(dll_t& dll, uint16_t mi, uint16_t si, Mutator&& mutator);
}
WriteOutputFramereplaces the complete RxPDO unconditionally and is for a single real-time owner only; it must not be used for partial writes. It returnsPdoWriteResultinstead ofbool:Busy(a brief collision with the real-time send/receive thread, where a later retry may succeed) is reported separately from permanent failures such asSizeMismatch/Failed, and once the retry budget is exhausted it returnsBusyas-is. An unconditional whole-frame write is idempotent, so retries produce no external side effects.PatchOutputFrame/MutateOutputFrameuse a versioned partial commit: take a snapshot → change bytes → commit the whole frame.
Parameters:
dll(dll_t&) — DLL contextmi(uint16_t) — master indexsi(uint16_t) — slave index (1-based)data(const uint8_t* / const void*) — the bytes to writesize(uint32_t / size_t) — byte countoffset(size_t) — byte offset relative to the start of the output process imagemutator(Mutator&&) — receives thestd::vector<uint8_t>&frame to be committed; returningfalseabandons this commit; it must be repeatable and must not produce external side effects
Return value:
WriteOutputFrame—PdoWriteResult. The criterion for a complete whole-frame write isSucceeded(requestedSize), that isstatus == PdoIoStatus::Ok && written == requestedSize && required == requestedSize.PatchOutputFrame/MutateOutputFrame—bool, whether the commit succeeded.
Description:
- A partial commit that hits a conflict / busy state automatically restarts from a fresh snapshot; an exhausted retry budget or any single failed commit returns
false. WriteOutputFramemay only be called by the single real-time owner of this slave's outputs; do not use it for partial semantics outside a whole replacement.- For partial writes use
PatchOutputFrame/MutateOutputFrameor the element accessors.
- For partial writes use
Example:
const uint16_t cw = 0x000F;
if (!darra::SlavePDO::PatchOutputFrame(dll, mi, 1, 0, &cw, sizeof(cw)))
std::printf("局部写失败\n"); // 2 bytes from offset 0
if (!darra::SlavePDO::MutateOutputFrame(dll, mi, 1, [](std::vector<uint8_t>& frame) {
if (frame.size() < 2) return false;
frame[1] |= 0x01;
return true;
}))
std::printf("版本化局部提交失败\n"); // Versioned partial commit failed\n
uint8_t out[4] = {0x0F, 0x00, 0x00, 0x00};
auto wr = darra::SlavePDO::WriteOutputFrame(dll, mi, 1, out, sizeof(out));
if (!wr.Succeeded(sizeof(out))) {
// wr.status == PdoIoStatus::Busy -> can be retried later; everything else is a permanent failure
}
ReadInputValue<T>() / ReadOutputValue<T>()
namespace darra::SlavePDO {
template<typename T>
std::optional<T> ReadInputValue(dll_t& dll, uint16_t mi, uint16_t si, int offset);
template<typename T>
std::optional<T> ReadOutputValue(dll_t& dll, uint16_t mi, uint16_t si, int offset);
}
Reads a T from byte offset offset of one complete snapshot, decoded little-endian. A frame that cannot be fetched or an offset that is out of range always returns std::nullopt —
no throw, no partial read.
Parameters:
dll(dll_t&) — DLL contextmi(uint16_t) — master indexsi(uint16_t) — slave index (1-based)offset(int) — byte offset relative to the start of this slave's process data area for this direction
Return value:
std::optional<T>— the value read;std::nulloptwhen out of range or on failure
Example:
if (auto v = darra::SlavePDO::ReadInputValue<uint32_t>(dll, mi, 1, 4))
std::printf("0x%08X\n", *v);
ReadInt8() / ReadUInt16() and the fixed-width read family
namespace darra::SlavePDO {
std::optional<int8_t> ReadInt8 (dll_t& dll, uint16_t mi, uint16_t si, int offset);
std::optional<int16_t> ReadInt16 (dll_t& dll, uint16_t mi, uint16_t si, int offset);
std::optional<int32_t> ReadInt32 (dll_t& dll, uint16_t mi, uint16_t si, int offset);
std::optional<int64_t> ReadInt64 (dll_t& dll, uint16_t mi, uint16_t si, int offset);
std::optional<uint8_t> ReadUInt8 (dll_t& dll, uint16_t mi, uint16_t si, int offset);
std::optional<uint16_t> ReadUInt16(dll_t& dll, uint16_t mi, uint16_t si, int offset);
std::optional<uint32_t> ReadUInt32(dll_t& dll, uint16_t mi, uint16_t si, int offset);
std::optional<uint64_t> ReadUInt64(dll_t& dll, uint16_t mi, uint16_t si, int offset);
std::optional<float> ReadFloat (dll_t& dll, uint16_t mi, uint16_t si, int offset);
std::optional<double> ReadDouble(dll_t& dll, uint16_t mi, uint16_t si, int offset);
}
Fixed-width wrappers around ReadInputValue<T>(): each takes a complete input snapshot by type name and decodes it. Parameters and return values are the same as above; failure returns
std::nullopt.
Example:
auto rawPos = darra::SlavePDO::ReadInt32(dll, mi, 1, 2); // 4 bytes from offset 2
if (!rawPos)
std::printf("位置读不到,不要当成 0\n"); // Position could not be read, do not treat it as 0\n
int32_t pos = rawPos ? *rawPos : 0;
auto rawSw = darra::SlavePDO::ReadUInt16(dll, mi, 1, 0); // StatusWord
uint16_t sw = rawSw.value_or(0x0000); // Explicit default; unknown and a real 0 are still told apart by rawSw.has_value()
WriteInt8() / WriteUInt16() and the fixed-width write family
namespace darra::SlavePDO {
bool WriteInt8 (dll_t& dll, uint16_t mi, uint16_t si, int offset, int8_t value);
bool WriteInt16 (dll_t& dll, uint16_t mi, uint16_t si, int offset, int16_t value);
bool WriteInt32 (dll_t& dll, uint16_t mi, uint16_t si, int offset, int32_t value);
bool WriteInt64 (dll_t& dll, uint16_t mi, uint16_t si, int offset, int64_t value);
bool WriteUInt8 (dll_t& dll, uint16_t mi, uint16_t si, int offset, uint8_t value);
bool WriteUInt16(dll_t& dll, uint16_t mi, uint16_t si, int offset, uint16_t value);
bool WriteUInt32(dll_t& dll, uint16_t mi, uint16_t si, int offset, uint32_t value);
bool WriteUInt64(dll_t& dll, uint16_t mi, uint16_t si, int offset, uint64_t value);
bool WriteFloat (dll_t& dll, uint16_t mi, uint16_t si, int offset, float value);
bool WriteDouble(dll_t& dll, uint16_t mi, uint16_t si, int offset, double value);
}
Fixed-width wrappers around WriteOutputValue<T>() that use a versioned partial commit with the same semantics as PatchOutputFrame().
Parameters:
dll(dll_t&) — DLL contextmi(uint16_t) — master indexsi(uint16_t) — slave index (1-based)offset(int) — byte offset; a negative value fails immediatelyvalue— the value to write
Return value:
bool— whether the commit succeeded; an illegaloffsetor a failed whole-frame commit returnsfalse
Example:
if (!darra::SlavePDO::WriteInt32(dll, mi, 1, 2, 10000)) // Partial write, sent next cycle
std::printf("写位置失败\n"); // Failed to write position\n
if (!darra::SlavePDO::WriteUInt16(dll, mi, 1, 0, 0x000F))
std::printf("写控制字失败\n"); // Failed to write control word\n
ReadString() / WriteString()
namespace darra::SlavePDO {
std::optional<std::string> ReadString(dll_t& dll, uint16_t mi, uint16_t si,
int offset, int maxLen);
bool WriteString(dll_t& dll, uint16_t mi, uint16_t si, int offset,
const std::string& value, int maxLen);
}
Reads and writes a fixed-length string field by byte offset; a read strips trailing null characters. A write measures length in UTF-8 bytes: an over-long value is rejected, not truncated; when the length fits, the value is written and the remaining bytes of the field are zero-filled (guaranteeing the terminating NUL).
Parameters:
dll(dll_t&) — DLL contextmi(uint16_t) — master indexsi(uint16_t) — slave index (1-based)offset(int) — byte offsetmaxLen(int) — field length in bytes, including the terminating null character (writable bytes = maxLen-1)value(const std::string&) — the content to write
Return value:
std::optional<std::string>— the string read;std::nulloptwhen out of range or the snapshot is unavailablebool—true= written;false= invalid argument / rejected as too long (both unwritten) / whole-frame commit failed
Description:
- The read direction locates the field by
offsetandmaxLen;offset < 0,maxLen < 0or a field beyond the frame length returnsstd::nullopt. - The returned content has trailing null characters removed; when the field contains no null character, the whole
maxLenlength is kept. - The write direction measures length in UTF-8 bytes and does not truncate: when the byte count exceeds
maxLen-1it rejects the write, returnsfalseand logs a Warning carrying the concrete byte count (writing half a string and still reporting success would mean data is swallowed); when the length fits it writes and zero-fills the remaining bytes of the field (including the terminating NUL).offset < 0ormaxLen <= 0likewise returnsfalseand logs a Warning, with nothing written. A failed whole-frame commit also returnsfalse.
Example:
if (auto name = darra::SlavePDO::ReadString(dll, mi, 1, 6, 16))
std::printf("name=%s\n", name->c_str());
if (!darra::SlavePDO::WriteString(dll, mi, 1, 6, "Axis-01", 16))
std::printf("写字符串失败\n"); // maxLen=16 includes the terminating null, so 15 bytes can be written
PDO mapping queries and startup policy
Mapping enumeration, offsets, sizes, probe policy, Bool layout and the checked versioned read/write entry points are provided by the shipped C header, and the C++ header does not define them again; when needed, include ethercat.hpp directly and use the copy in the C header. For signatures and parameter descriptions see the C SDK PDO page. All of this is computed inside the runtime library; the SDK does not recompute mapping entries or bit offsets in the upper layer, and this page does not repeat those C entry points.
The C++ side has one more entry for the typed mirror of the input parameters:
| Category | Method | Return type | Read/write | Description |
|---|---|---|---|---|
| Startup policy | PdoResolveStartupPolicy(in, out) | int | read-only | Startup PDO Assignment / Mapping decision tree; 0 = success |
PdoResolveStartupPolicy()
namespace darra::ethercat {
struct PdoStartupPolicyIn { // 8 bytes, matching the runtime in-parameters field by field
uint8_t slave_has_own_pdo;
uint8_t esi_allow_assignment;
uint8_t esi_allow_configuration;
uint8_t all_pdo_fixed;
uint8_t has_init_cmd;
uint8_t has_alt_sm_mapping;
uint8_t init_cmd_requires_explicit;
uint8_t probe_enabled;
};
struct PdoStartupPolicyOut { // 5 bytes, matching the runtime out-parameters field by field
uint8_t action; // 0=generate everything 1=return empty 2=generate AltSm then return 3=Mapping only
uint8_t write_assignment;
uint8_t write_configuration;
uint8_t resolved_valid;
uint8_t resolved_value;
};
inline int PdoResolveStartupPolicy(const PdoStartupPolicyIn* in, PdoStartupPolicyOut* out);
}
The decision tree for Startup PDO Assignment / Mapping. The C++ side provides typed input with named fields; the field order matches the underlying input and output parameters byte for byte, and the pointers are passed straight through.
Return value:
int— 0 = success; a negative value = failure (invalid argument / not ready)
The parameter lists of the mapping queries / probe / checked versioned reads and writes are the same as on the C++ side and are not redefined by the C++ header: after including ethercat.hpp, use the copy in the C header; for signatures and parameter descriptions see the C SDK PDO page.
They already use versioned partial commits, so you do not have to manage the commit details yourself; call the checked versioned entry points in the C header directly only when you really need to manage them yourself (see the C SDK PDO page).
Full example
#include "ethercat.hpp"
#include <cstdio>
#include <vector>
#pragma pack(push, 1)
struct InPdo { uint16_t statusWord; int32_t actualPosition; };
struct OutPdo { uint16_t controlWord; int32_t targetPosition; };
#pragma pack(pop)
int main() {
dll_t dll;
darra::EtherCATMaster master(dll);
master.SetENI("C:\\EtherCAT\\MyProject.deni"); // DENI one-line load
if (!master.Build()) return 1;
if (!master.SetState(darra::EcState::OP)) return 1; // Enter OP
const uint16_t mi = master.MasterNumber();
const uint16_t si = 1; // Slave index, 1-based
// Struct mapping: map once, then reading/writing members reads/writes the process image (zero-copy)
const InPdo& in = darra::SlavePDO::InputsMapping<InPdo>(dll, mi, si);
OutPdo& out = darra::SlavePDO::OutputsMapping<OutPdo>(dll, mi, si);
out.controlWord = 0x000F; // Write: sent next cycle
out.targetPosition = in.actualPosition + 1000; // Read: current cycle
// Element view: read and write a single element by byte offset
darra::PDOArrayInstance inElem(dll, mi, si,
darra::SlavePDO::InputDataSize(dll, mi, si), true);
darra::PDOArrayInstance outElem(dll, mi, si,
darra::SlavePDO::OutputDataSize(dll, mi, si), false);
if (inElem.Length() >= 6)
std::printf("pos=%d\n", inElem[2].AsInt32()); // A fresh complete input snapshot
if (outElem.Length() > 0)
outElem[0].SetBit(0, true); // Set bit0 only, leave the rest of the byte alone
// Typed single point: read one value by byte offset
auto rawVel = darra::SlavePDO::ReadInt32(dll, mi, si, 6);
int32_t velocity = rawVel ? *rawVel : 0; // Give an explicit default when it cannot be read; do not forget rawVel.has_value()
// Whole-frame snapshot: one complete frame, one generation, copied out it does not follow the bus
std::vector<uint8_t> frame;
if (darra::SlavePDO::CopyInputFrame(dll, mi, si, frame) && frame.size() >= 2)
std::printf("快照 %zu 字节, status=0x%04X\n", frame.size(), // Snapshot %zu bytes, status=0x%04X\n
static_cast<unsigned>(frame[0] | (frame[1] << 8)));
std::printf("status=0x%04X pos=%d vel=%d\n",
static_cast<unsigned>(in.statusWord), in.actualPosition, velocity);
std::getchar();
return 0; // master destructor: Stop + Dispose automatically
}