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.
- 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 (Recommended)
- Compiling a single line in MSVC
- GCC / Clang
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)
cl /utf-8 /I<sdk>\include main.c /link <sdk>\build\Darra.OpcUa.Core.lib
gcc -I<sdk>/include main.c -L<sdk>/build -lDarra.OpcUa.Core -o my_app
System Requirements
| Item | Requirements |
|---|---|
| Operating System | Windows 10/11 x64 |
| Platform | x64 |
| Agreement | OPC UA TCP (opc.tcp://) |
| Library | Darra.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):
| Module | Header Files | Uses |
|---|---|---|
| Safe API | opcua_safe.h | BrowseSafe / ReadSafe / WriteSafe / CallSafe / ReadHistorySafe |
| Filter | opcua_filter.h | DataChangeFilter / EventFilter / Triggering |
| NodeId Strongly Typed | opcua_node_id.h | OwnedNodeId + Parse / ToString / Well-Known |
| NumericRange | opcua_numeric_range.h | NumericRange + ReadRange / WriteRange |
| ServerInfo | opcua_server_info.h | ServerStatus + BuildInfo |
| BrowseCrawler | opcua_browse_crawler.h | Browse Full-Tree Crawling (Callback-Based) |
| MethodBuilder | opcua_method_builder.h | Method: Calling a Stream Constructor |
| HistoryStream | opcua_history_stream.h | History Page Iterator |
| FileTransfer | opcua_file_transfer.h | FileType Client |
| Alarm | opcua_alarm.h | Alarms & Conditions (10 Method) |
| StructDecoder | opcua_struct_decoder.h | Variant ExtensionObject Decode |
Main Types:
| Type | Uses |
|---|---|
| DarraUa_SessionHandle | Session handle (uint32_t, 0 = invalid) |
| DarraUa_SubscriptionHandle | Subscription Handle |
| DarraUa_MonitoredItemHandle | MonitoredItem 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_Status | StatusCode (uint32_t, 0 = Good) |
| DarraUa_NodeClass / DarraUa_AttributeId | OPC 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
| Feature | Entry API | Description |
|---|---|---|
| Library Initialization / Unloading | DarraUa_Initialize / DarraUa_Shutdown | Process-level, internal reference counting |
| Create a Session | DarraUa_Session_Create(&cfg, &h) | Do not connect |
| Connect / Disconnect | DarraUa_Session_Connect / Disconnect / Close | None / Sign / SignAndEncrypt + Anonymous / Username |
| Single-Point Read/Write | DarraUa_Session_ReadNode / WriteNode | Strings NodeId Convenience API |
| Batch Read | DarraUa_Session_ReadNodes / Read | Once RPC, N nodes |
| Browse | DarraUa_Session_BrowseNode / Browse / BrowseNodes / BrowseNext | Includes pagination support |
| Path Resolution | DarraUa_Session_TranslateBrowsePaths / ResolveBrowsePath | Browse Path → NodeId |
| Registration Node | DarraUa_Session_RegisterNodes / UnregisterNodes | Reduces server-side parsing overhead during frequent, repeated requests to the same node (benefits based on actual server-side testing) |
| Data Subscriptions | DarraUa_Subscription_Create + _AddNode / _AddNodes | publishing / sampling, two-layer |
| Event Subscription | DarraUa_Subscription_AddEventItem (opcua_event.h) | Alarms & Conditions |
| Adjustment Methods | DarraUa_Session_Call(...) | OPC UA Method Node |
| History Reading | DarraUa_Session_HistoryReadRaw / DarraUa_Session_HistoryReadModified / DarraUa_Session_HistoryReadAtTime / DarraUa_Session_HistoryReadProcessed / DarraUa_Session_HistoryReadEvents | 5 Modes |
| Writing History | DarraUa_Session_HistoryUpdateData / DarraUa_Session_HistoryDeleteRange | Insert / Replace / Update / Remove |
| Heartbeat | cfg.keepalive_interval_ms | Background Periodic Monitoring |
| Automatic Reconnection | cfg.auto_reconnect = 1 | Detect a disconnection → Reconnect |
| Service Discovery | DarraUa_Discovery_GetEndpoints / DarraUa_Discovery_FindServers | No session required |
| Namespace | DarraUa_Session_GetNamespaceUri / FindNamespaceIndex | Anti-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).
| Allocation | Release |
|---|---|
| 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 Item | DarraUa_Free(out_node_ids[i]) |
| "Raw Buffers" in Stack's Internal malloc | DarraUa_Free(p) |
Handles (uint32_t) are managed by the stack pool; do not free():
| Handle | Close |
|---|---|
| DarraUa_SessionHandle | DarraUa_Session_Close(h) |
| DarraUa_SubscriptionHandle | DarraUa_Subscription_Delete(sub) |
| DarraUa_MonitoredItemHandle | DarraUa_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.
| Operations | C# (DarraOpcUa) | C |
|---|---|---|
| Database Initialization | (Implicit) | DarraUa_Initialize() |
| Create a Session | new DarraOpcUa(url) | DarraUa_Session_Create(&cfg, &h) |
| Connect | ua.Connect() | DarraUa_Session_Connect(h) |
| Read Single Node | ua.Read("i=2258") | DarraUa_Session_ReadNode(h, "i=2258", attr, &st) |
| Order-Writing Node | ua.Write(id, v) | DarraUa_Session_WriteNode(h, id, attr, v) |
| Browse | ua.Browse("i=84") | DarraUa_Session_BrowseNode(h, "i=84", filter, &res) |
| Create a Subscription | ua.CreateSubscription(500) | DarraUa_Subscription_Create(h, &cfg, &sub) |
| Subscribe to a node | sub.Add("i=2258") | DarraUa_Subscription_AddNode(sub, "i=2258", attr, smpl, cb, ctx, &mi) |
| Pump | ua.Publish(2000) | DarraUa_Session_Publish(h, 2000) |
| Destroy | using var ua | DarraUa_Session_Close(h) |
Just read through the left sidebar in order to master everything C ABI.