跳到主要内容

NodeCollection (C 中无对等体)

C# 提供 ua.Nodes["ns=2;s=Foo"] 这种 Lazy Load 索引器, C SDK 没有对等体 — C 没有运算符重载, 也不维护持久节点对象, 一切都是直接对 NodeId 字符串调 API.

前置阅读

C# 写法 → C 写法对照

1. 字符串 NodeId 直接读

// C#
using var dv = ua.Nodes["ns=2;s=Temperature"].Value;
/* C */
DarraUa_Status st = 0;
DarraUa_DataValue* dv = DarraUa_Session_ReadNode(
h, "ns=2;s=Temperature", DARRA_UA_ATTR_VALUE, &st);
/* 用完 */
DarraUa_DataValue_Delete(dv);

2. 链式索引器 (Server.ServerStatus.CurrentTime)

// C# - 4 次 Browse + 1 次 Read
using var dv = ua.Nodes.Server["ServerStatus"]["CurrentTime"].Value;

C 推荐方式: 用 ResolveBrowsePath 一次性解析路径, 而不是逐段 Browse:

/* C - 1 次 ResolveBrowsePath + 1 次 Read */
char node_id[128];
int32_t n = DarraUa_Session_ResolveBrowsePath(
h, "i=2253" /* Server */,
"/ServerStatus/CurrentTime",
node_id, (int32_t)sizeof(node_id));
if (n > 0) {
DarraUa_Status st = 0;
DarraUa_DataValue* dv = DarraUa_Session_ReadNode(
h, node_id, DARRA_UA_ATTR_VALUE, &st);
DarraUa_DataValue_Delete(dv);
}

或更直接 — Server.ServerStatus.CurrentTime 是标准节点, 直接用宏:

DarraUa_DataValue* dv = DarraUa_Session_ReadNode(
h, "i=2258" /* CurrentTime */, DARRA_UA_ATTR_VALUE, &st);

自实现一个简单 cache (推荐)

如果业务上经常按 BrowsePath 找 NodeId, 自己写个 path → NodeId map:

typedef struct {
char path[256];
char node_id[128];
} PathCacheEntry;

static PathCacheEntry g_cache[1024];
static int g_cache_count = 0;

static const char* resolve_cached(DarraUa_SessionHandle h,
const char* start, const char* path)
{
/* 1. 查缓存 */
char key[256];
snprintf(key, sizeof(key), "%s|%s", start, path);
for (int i = 0; i < g_cache_count; ++i) {
if (strcmp(g_cache[i].path, key) == 0)
return g_cache[i].node_id;
}
/* 2. 解析后入缓存 */
if (g_cache_count >= 1024) return NULL;
PathCacheEntry* e = &g_cache[g_cache_count];
int32_t n = DarraUa_Session_ResolveBrowsePath(
h, start, path, e->node_id, (int32_t)sizeof(e->node_id));
if (n <= 0) return NULL;
snprintf(e->path, sizeof(e->path), "%s", key);
g_cache_count++;
return e->node_id;
}

何时用各种方式

场景推荐
已知精确 NodeId字符串 DarraUa_Session_ReadNode
标准节点 (Server 状态等)WellKnownNodes
浏览树 / 写一次性脚本DarraUa_Session_BrowseNode
批量 (100+ 节点)DarraUa_Session_ReadNodes / _BrowseNodes, 不要循环
100+ 路径批量初始化DarraUa_Session_TranslateBrowsePaths

下一步