Skip to main content

Darra OPC UA Client — C++ SDK

Darra OPC UA Client C++ Bindings. header-only, C++17, RAII, Namespaces darra::opcua. The concept hierarchy is consistent with C# (Session / Subscription / Variant / DataValue), and the specific API syntax has been adjusted to conform to C++ conventions — seeCross-Language Alignment.

Chapter Navigation
  • Getting Started → Session (Construct / Connect / Read / Write / KeepAlive)
  • Browse → Nodes (Browse / Path Resolution / RegisterNodes)
  • Real-time → Subscription (CreateSubscription / MonitoredItem / on_data_change)
  • History → History (Raw / Modified / AtTime / Processed / Events / Update / Delete)
  • Call → Method (Call)
  • Discover → Discovery (GetEndpoints / FindServers)
  • Data → Data Types (Variant / DataValue / WellKnownNodes)
  • Security → Security (Certificates / Encryption)

Installation​

C++ SDK is header-only, There is no need to compile the .cpp files separately. Simply Darra.OpcUa.Core add the include/ directories where the C++ and C packages were extracted to the project's include path, and then link the C implementation.

add_executable(my_app main.cpp)

target_include_directories(my_app PRIVATE
${CMAKE_SOURCE_DIR}/third_party/darra_opcua_cpp/include
${CMAKE_SOURCE_DIR}/third_party/darra_opcua_c/include)

target_link_libraries(my_app PRIVATE Darra.OpcUa.Core)
target_compile_features(my_app PRIVATE cxx_std_17)

System Requirements​

ItemRequirements
CompilerC++17
Operating SystemWindows 10/11 x64
Platformx64
AgreementOPC UA TCP (opc.tcp://)

Namespace​

#include <darra/opcua/client.hpp>           // Session / Variant / DataValue / Subscription
#include <darra/opcua/discovery.hpp> // Discovery::GetEndpoints / FindServers
#include <darra/opcua/history.hpp> // HistoryAggregate / HistoryUpdateType
#include <darra/opcua/well_known_nodes.hpp> // Standard Node Constants

using namespace darra::opcua;

Main Types:

C++ TypesC# EquivalentUses
darra::opcua::SessionDarraOpcUaClient Superclass (One Session)
darra::opcua::SubscriptionOpcUaSubscriptionData Subscription Container
darra::opcua::EventSubscriptionOpcUaEventSubscriptionEvent Subscriptions (Alarms & Conditions)
darra::opcua::NodeCollection / NodeNodeCollection / OpcUaNodeLazy Load Node Access
darra::opcua::Variant / DataValueSame NameData Encapsulation
darra::opcua::Discovery (static)Same NameGetEndpoints / FindServers
darra::opcua::WellKnownNodes (static)Same NameOPC Foundation Standard Node Constants
darra::opcua::ExceptionOpcUaExceptionExceptions associated StatusCode with "carry"

Quick Start in One Minute​

#include <darra/opcua/client.hpp>
#include <iostream>

using namespace darra::opcua;

int main() {
Stack::Init(); // Global Initialization
{
Session s("opc.tcp://localhost:4840"); // RAII, Stack Object
s.Connect();

// Read
auto dv = s.Read("ns=2;s=Temperature");
std::cout << "Temperature = " << dv.Value().AsString() << " degC\n";

// Write
Variant v; v.SetDouble(42.0);
s.Write("ns=2;s=Setpoint", v);

// Subscribe
auto sub = s.CreateSubscription(500.0);
sub.AddNode("ns=2;s=Counter", [](DataValue const& dv) {
std::cout << "Counter = " << dv.Value().AsString() << "\n";
});
} // Session Destruction (Automatic Close)
Stack::Shutdown();
return 0;
}

Session The destructor will be called DarraUa_Session_Close, soFirst, let it finish s its destructor, then Stack::Shutdown(), Do not reverse the order.

Advanced API Overview​

FeatureEntry APIDescription
Connection / EncryptionSession(...) + s.Connect()None / Sign / SignAndEncrypt + Anonymous / Username
Single-Point Read/Writes.Read / s.WriteSingle Node, Single Attribute
Batch Reads.ReadMany(node_ids[, attr])Once RPC, N nodes
Browse Trees.Browse / BrowseMany / BrowseWithPaging / BrowseNextFull pagination support
Path Resolutions.Resolve / TranslateBrowsePathsBrowse Path → NodeId
Registration Nodes.RegisterNodes / UnregisterNodesThe server returns a temporary object with a lifecycle of "Session NodeId."
Data Subscriptionss.CreateSubscription + sub.AddNode / AddManypublishing / sampling, two-layer
Event Subscriptions.SubscribeEventsAlarms & Conditions
Adjustment Methodss.Call(obj_id, mtd_id, inputs)OPC UA Method Node
History Readings.ReadHistory / ReadHistoryModified / AtTime / Processed / Events5 Modes
History Writings.UpdateHistory / DeleteHistoryRangeInsert / Replace / Update / Delete
Heartbeats.SetKeepAliveInterval(ms)Background Periodic Monitoring
Automatic Reconnection(Built-in; controlled by ConnectionConfig.auto_reconnect)Try again after reconnecting TransferSubscriptions; if that fails, clear the local subscription table.
Unified Events.Events().on_*Current Automatic Push StateChanged / KeepAlive (two types) + Communication Errors
Service DiscoveryDiscovery::GetEndpoints / FindServersNo session required

RAII And Exceptions​

The C++ SDK makes every resource RAII: stack objects manage their own lifetime, so do not use new — destructors free everything. Errors are uniformly thrown as darra::opcua::Exception, which carries status_code() / status():

try {
Session s("opc.tcp://localhost:4840");
s.Connect();
auto dv = s.Read("ns=2;s=NotExist");
} catch (Exception const& ex) {
std::cerr << "OPC UA error: " << ex.what()
<< " status=0x" << std::hex << ex.status_code() << std::dec << "\n";
if (ex.status() == Status::BadNodeIdUnknown) { /* Processing */ }
}

Move-only semantics​

Subscription / EventSubscription / Variant / DataValue Cannot be copied but can be moved (like std::unique_ptr):

auto sub1 = s.CreateSubscription(500.0);
// Subscription sub2 = sub1; // Compilation error: copy constructor deleted
Subscription sub2 = std::move(sub1); // OK, Expires sub1 thereafter

Session Cannot be copied or moved —— It only declares Session(Session const&) = delete and operator=(Session const&) = delete, with no move construct. To transfer a session, use std::unique_ptr<Session> to pass it along.

As a result, the resource will not be released twice.

FileTime Time Arrangement​

All History API times are expressed in FileTime (UTC 100ns since 1601-01-01), consistent with Windows DateTime.ToFileTimeUtc():

constexpr int64_t WIN_EPOCH_OFFSET = 116444736000000000LL;  // 1601 → 1970 interval

auto now_ns = std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::system_clock::now().time_since_epoch()).count();
int64_t now_ft = WIN_EPOCH_OFFSET + now_ns / 100;

Cross-Language Alignment​

The API naming and behavior of the C# SDK are the reference implementation for the other language bindings. The Java, Python, C++, Rust, and C bindings follow their own language conventions, but the semantics are consistent (e.g. C# ua.Read(...) ↔ C++ s.Read(...) ↔ Python ua.read(...)). Start with C#; switching to another language later only requires renaming — the concepts and semantics stay the same.

ButNot every line has the same API shape, C++ has its own limitations (see the respective pages for details):

  • The session type in C++ is darra::opcua::Session, and in C# it is DarraOpcUa
  • C++ is largelyMethods(dv.Value() / dv.SourceTimestamp()), not a property field
  • The state type in C++ is enum class Status, not StatusCode
  • C++ does not have Reconnect(), does not have subscription-based recovery, and does not have subscription EventFilter overloads with DataChangeFilter /

Just read through the left sidebar in order to master everything SDK API.