Skip to main content

Darra OPC UA Client — C SDK

Darra OPC UA Client The lowest-level external interface of the protocol stack, which also serves as the common foundation for the C#, Java, Python, C++, and Rust language bindings. Unlike other languages, C: The user does not have a wrapper class — Simply #include <opcua/opcua.h> call the series DarraUa_* of functions C ABI.

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

Installation​

cmake_minimum_required(VERSION 3.16)
project(my_opcua_app C)

set(SDK_ROOT "/path/to/darra_opcua_c")
add_executable(my_app main.c)
target_include_directories(my_app PRIVATE "${SDK_ROOT}/include")
target_link_directories(my_app PRIVATE "${SDK_ROOT}/build")
target_link_libraries(my_app PRIVATE Darra.OpcUa.Core)

System Requirements​

ItemRequirements
Operating SystemWindows 10/11 x64
Platformx64
AgreementOPC UA TCP (opc.tcp://)
LibraryDarra.OpcUa.Core.dll

Header Files​

The main ABI entry point of the protocol stack is <opcua/opcua.h>, which already includes the status, types, session, and subscribe subheaders. History and event subscriptions are added on demand:

#include <opcua/opcua.h>            /* Session + Browse + Subscription */
#include <opcua/opcua_history.h> /* HistoryRead / HistoryUpdate */
#include <opcua/opcua_event.h> /* Event Subscriptions (Alarms & Conditions) */

The C SDK has one more entry point for extensions, <opcua_sdk.h>, which pulls in all 11 extension modules in a single line (each module can also be included individually):

ModuleHeader FilesUses
Safe APIopcua_safe.hBrowseSafe / ReadSafe / WriteSafe / CallSafe / ReadHistorySafe
Filteropcua_filter.hDataChangeFilter / EventFilter / Triggering
NodeId Strongly Typedopcua_node_id.hOwnedNodeId + Parse / ToString / Well-Known
NumericRangeopcua_numeric_range.hNumericRange + ReadRange / WriteRange
ServerInfoopcua_server_info.hServerStatus + BuildInfo
BrowseCrawleropcua_browse_crawler.hBrowse Full-Tree Crawling (Callback-Based)
MethodBuilderopcua_method_builder.hMethod: Calling a Stream Constructor
HistoryStreamopcua_history_stream.hHistory Page Iterator
FileTransferopcua_file_transfer.hFileType Client
Alarmopcua_alarm.hAlarms & Conditions (10 Method)
StructDecoderopcua_struct_decoder.hVariant ExtensionObject Decode

Main Types:

TypeUses
DarraUa_SessionHandleSession handle (uint32_t, 0 = invalid)
DarraUa_SubscriptionHandleSubscription Handle
DarraUa_MonitoredItemHandleMonitoredItem Handle
DarraUa_Variant*Generic Value Container (opaque)
DarraUa_DataValue*Read the full value (opaque) returned
DarraUa_BrowseResult*Browse List of returned child nodes (opaque)
DarraUa_StatusStatusCode (uint32_t, 0 = Good)
DarraUa_NodeClass / DarraUa_AttributeIdOPC UA Enumeration

Delay​

In the demo, use directly for <windows.h> the wait Sleep(ms):

#include <windows.h>
#define OPCUA_SLEEP_MS(ms) Sleep(ms)
#define OPCUA_SLEEP_SEC(s) Sleep((s) * 1000)

Quick Start in One Minute​

#include <opcua/opcua.h>
#include <stdio.h>

int main(int argc, char** argv)
{
const char* endpoint = (argc >= 2) ? argv[1] : "opc.tcp://localhost:4840";

/* 1. Library Initialization */
DarraUa_Initialize();

/* 2. Configuration + Creating a Session */
DarraUa_SessionConfig cfg;
DarraUa_SessionConfig_Init(&cfg);
cfg.endpoint_url = endpoint;
cfg.security_mode = UA_MSG_SECURITY_MODE_NONE;
cfg.security_policy_uri = "http://opcfoundation.org/UA/SecurityPolicy#None";
cfg.user_token_type = UA_USER_TOKEN_ANONYMOUS;

DarraUa_SessionHandle h = UA_INVALID_SESSION_HANDLE;
DarraUa_Session_Create(&cfg, &h);
DarraUa_Session_Connect(h);

/* 3. Read ServerStatus.CurrentTime */
DarraUa_Status st = 0;
DarraUa_DataValue* dv = DarraUa_Session_ReadNode(
h, "i=2258", UA_ATTR_VALUE, &st);
if (dv && UA_STATUS_IS_GOOD(st)) {
const DarraUa_Variant* v = DarraUa_DataValue_GetValue(dv);
DarraUa_DateTime ft = DarraUa_Variant_GetDateTime(v);
printf("CurrentTime ft=%lld\n", (long long)ft);
DarraUa_DataValue_Delete(dv);
}

/* 4. Reverse Cleaning */
DarraUa_Session_Disconnect(h);
DarraUa_Session_Close(h);
DarraUa_Shutdown();
return 0;
}

Advanced API Overview​

FeatureEntry APIDescription
Library Initialization / UnloadingDarraUa_Initialize / DarraUa_ShutdownProcess-level, internal reference counting
Create a SessionDarraUa_Session_Create(&cfg, &h)Do not connect
Connect / DisconnectDarraUa_Session_Connect / Disconnect / CloseNone / Sign / SignAndEncrypt + Anonymous / Username
Single-Point Read/WriteDarraUa_Session_ReadNode / WriteNodeStrings NodeId Convenience API
Batch ReadDarraUa_Session_ReadNodes / ReadOnce RPC, N nodes
BrowseDarraUa_Session_BrowseNode / Browse / BrowseNodes / BrowseNextIncludes pagination support
Path ResolutionDarraUa_Session_TranslateBrowsePaths / ResolveBrowsePathBrowse Path → NodeId
Registration NodeDarraUa_Session_RegisterNodes / UnregisterNodesReduces server-side parsing overhead during frequent, repeated requests to the same node (benefits based on actual server-side testing)
Data SubscriptionsDarraUa_Subscription_Create + _AddNode / _AddNodespublishing / sampling, two-layer
Event SubscriptionDarraUa_Subscription_AddEventItem (opcua_event.h)Alarms & Conditions
Adjustment MethodsDarraUa_Session_Call(...)OPC UA Method Node
History ReadingDarraUa_Session_HistoryReadRaw / DarraUa_Session_HistoryReadModified / DarraUa_Session_HistoryReadAtTime / DarraUa_Session_HistoryReadProcessed / DarraUa_Session_HistoryReadEvents5 Modes
Writing HistoryDarraUa_Session_HistoryUpdateData / DarraUa_Session_HistoryDeleteRangeInsert / Replace / Update / Remove
Heartbeatcfg.keepalive_interval_msBackground Periodic Monitoring
Automatic Reconnectioncfg.auto_reconnect = 1Detect a disconnection → Reconnect
Service DiscoveryDarraUa_Discovery_GetEndpoints / DarraUa_Discovery_FindServersNo session required
NamespaceDarraUa_Session_GetNamespaceUri / FindNamespaceIndexAnti-Drift ns

Memory Ownership​

C None RAII / GC, All "return heap objects" must API call the corresponding _Delete. Whoever allocates, releases: Objects allocated by the Stack must be released _Delete using the Stack's built-in release function; never mix methods. free() (Cross-platform DLL CRT inconsistencies will cause a crash).

AllocationRelease
DarraUa_Variant_New()DarraUa_Variant_Delete(v)
DarraUa_Session_ReadNode(...)DarraUa_DataValue_Delete(dv)
DarraUa_Session_BrowseNode(...)DarraUa_BrowseResult_Delete(br)
DarraUa_Session_HistoryReadRaw(...)DarraUa_DataValueArray_Delete(arr, count)
DarraUa_Session_HistoryReadEvents(...)DarraUa_EventArray_Delete(arr, count)
DarraUa_Session_Call(...)DarraUa_VariantArray_Delete(arr, count)
DarraUa_Discovery_GetEndpoints(...)DarraUa_GetEndpointsResult_Delete(r)
DarraUa_Session_TranslateBrowsePaths(...) Single ItemDarraUa_Free(out_node_ids[i])
"Raw Buffers" in Stack's Internal mallocDarraUa_Free(p)

Handles (uint32_t) are managed by the stack pool; do not free():

HandleClose
DarraUa_SessionHandleDarraUa_Session_Close(h)
DarraUa_SubscriptionHandleDarraUa_Subscription_Delete(sub)
DarraUa_MonitoredItemHandleDarraUa_MonitoredItem_Delete(sub, mi)

Error Handling Template​

C: No exceptions; each one API returns DarraUa_Status:

DarraUa_Status st = DarraUa_Session_Connect(h);
if (!UA_STATUS_IS_GOOD(st)) {
fprintf(stderr, "connect failed: 0x%08X (%s)\n",
(unsigned)st, DarraUa_StatusName(st));
/* Execute cleanup, go to label */
}

Thread Models and Callbacks​

  • Callbacks are triggered by an internal thread in Stack (DLL internal thread pool), which is different from the calling thread.
  • In manual pump mode (call DarraUa_Session_Publish), the callback is triggered on the thread that called Publish.
  • Configure the background SDK thread DarraUa_Session_StartAutoPublish(h) to continue publishing
  • Concurrent calls within the same session must be serialized by the caller: Internal locks protect only the request handle count and the subscription table; they do not cover request paths such as Read, Write, etc Browse.
  • When accessing cross-thread shared data in a callback, be sure to use locks or atomic operations; do not perform lengthy calculations or cause blocking. IO

Cross-Language Alignment​

The functions exposed by the C SDK map one-to-one onto the C# SDK: C# ua.Read("ns=2;s=X") is equivalent to C DarraUa_Session_ReadNode(handle, "ns=2;s=X", attr, &status). For conceptual material (protocol / behavior) prefer the C# documentation; the C documentation only covers C-specific memory ownership and callback-thread semantics.

OperationsC# (DarraOpcUa)C
Database Initialization(Implicit)DarraUa_Initialize()
Create a Sessionnew DarraOpcUa(url)DarraUa_Session_Create(&cfg, &h)
Connectua.Connect()DarraUa_Session_Connect(h)
Read Single Nodeua.Read("i=2258")DarraUa_Session_ReadNode(h, "i=2258", attr, &st)
Order-Writing Nodeua.Write(id, v)DarraUa_Session_WriteNode(h, id, attr, v)
Browseua.Browse("i=84")DarraUa_Session_BrowseNode(h, "i=84", filter, &res)
Create a Subscriptionua.CreateSubscription(500)DarraUa_Subscription_Create(h, &cfg, &sub)
Subscribe to a nodesub.Add("i=2258")DarraUa_Subscription_AddNode(sub, "i=2258", attr, smpl, cb, ctx, &mi)
Pumpua.Publish(2000)DarraUa_Session_Publish(h, 2000)
Destroyusing var uaDarraUa_Session_Close(h)

Just read through the left sidebar in order to master everything C ABI.