C · recipe
Call an OPC UA method in C
UA_Client_call takes the owning object, the method node and an input argument array, and hands back an output array you must free. Check both the service result and the operation's own status.
| Stack | open62541 |
|---|---|
| Version | 1.5.8 |
The code
#include <open62541/client_config_default.h>
#include <open62541/client_highlevel.h>
#include <stdio.h>
int main(void) {
UA_Client *client = UA_Client_new();
UA_ClientConfig_setDefault(UA_Client_getConfig(client));
if (UA_Client_connect(client, "opc.tcp://localhost:4840") != UA_STATUSCODE_GOOD) {
UA_Client_delete(client); return 1;
}
UA_Double input = 16.0;
UA_Variant inArg;
UA_Variant_init(&inArg);
UA_Variant_setScalar(&inArg, &input, &UA_TYPES[UA_TYPES_DOUBLE]);
size_t outSize = 0;
UA_Variant *outArgs = NULL;
UA_StatusCode rc = UA_Client_call(client,
UA_NODEID_STRING(1, "Methods"), /* object that owns the method */
UA_NODEID_STRING(1, "Methods/sqrt"), /* the method itself */
1, &inArg, &outSize, &outArgs);
if (rc == UA_STATUSCODE_GOOD) {
printf("outputs: %zu\n", outSize);
for (size_t i = 0; i < outSize; i++)
if (outArgs[i].type == &UA_TYPES[UA_TYPES_DOUBLE])
printf(" %.1f\n", *(UA_Double *)outArgs[i].data);
UA_Array_delete(outArgs, outSize, &UA_TYPES[UA_TYPES_VARIANT]);
} else {
printf("call failed: %s\n", UA_StatusCode_name(rc));
}
UA_Client_disconnect(client);
UA_Client_delete(client);
return 0;
}
What it prints
outputs: 1
4.0
Notes
- The output array is yours to free. UA_Array_delete with UA_TYPES_VARIANT, exactly as above: this leaks quietly otherwise.
- You need both the object node id and the method node id. Browse the object to find the method.
- Input argument types must match the declared InputArguments, in order. Read that property first if you are unsure.
- Check the Executable attribute if a method exists but refuses to run.
What breaks first
The call is refused with an argument error
Read the method's InputArguments property for the declared count, order and types, and build the variant array to match.
BadArgumentsMissingRead the method's InputArguments property for the declared count, order and types, and build the variant array to match.
Other recipes in this stack
Concepts on this page
Last verified 7 September 2026 against OPC UA 1.05.07. OPC UA Connect is an educational resource and is not affiliated with the OPC Foundation.