How to convert const UA_Variant *input to std::string

373 views
Skip to first unread message

Vojtěch Houdek

unread,
Apr 27, 2022, 8:26:10 AM4/27/22
to open62541
Hello,
i am a junior dev in c ++ and i am trying to convert the parameter of the function "static UA_StatusCode ... (...., const UA_Variant * input)" inside the body of this function to the classic std::string data type. I've tried many ways and it still doesn't work. The input data are valid. When I  do convert I always get meaningless numbers.
I also tried to come up with an algorithm for conversion using the original value uint8_t which represents UA_Byte which is contained in UA_String.data, but none of this came out.

I hope it is understandable. Thank you for any response.

Jijun MA

unread,
Apr 29, 2022, 7:38:08 AM4/29/22
to Vojtěch Houdek, open62541
Hello,

this works for me:

#include <open62541/types_generated.h>
#include <open62541/types.h>
#include <iostream>
using namespace std;

void set_str_to_variant(UA_Variant *var) {
    char hello[] = "hello";
    auto ua_hello = UA_STRING(hello);
    UA_Variant_setScalarCopy(var, &ua_hello, &UA_TYPES[UA_TYPES_STRING]);
}

string get_str_from_variant(UA_Variant *var) {
    auto str = (UA_String *)var->data;
    return (char *)str->data;
}

int main()
{
    UA_Variant ua_var;

    set_str_to_variant(&ua_var);
    cout << get_str_from_variant(&ua_var);
}


From: open...@googlegroups.com <open...@googlegroups.com> on behalf of Vojtěch Houdek <vojt...@gmail.com>
Sent: Wednesday, April 27, 2022 20:26
To: open62541 <open...@googlegroups.com>
Subject: [open62541] How to convert const UA_Variant *input to std::string
 
--
You received this message because you are subscribed to the Google Groups "open62541" group.
To unsubscribe from this group and stop receiving emails from it, send an email to open62541+...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/open62541/22b37eac-18ce-45d6-b9f6-038f1561d355n%40googlegroups.com.

Julius Pfrommer

unread,
Apr 29, 2022, 12:30:21 PM4/29/22
to open62541
Thanks Kim for the solution.

I would make a small addition.
You are directly casting from (char*) to a std:string.
That works in this case because the original memory is zero-terminated.
But that is not always the case.

In open62541 we track the length of strings explicitly.
So you can build your std::string as follows:

std::string((char *)str->data, str->length);

That is even a speed improvement because there is no need to scan for the terminating zero.

Regards, Julius
Reply all
Reply to author
Forward
0 new messages