open62541pp 0.16.0
C++ wrapper of open62541
Loading...
Searching...
No Matches
typeconversion.cpp
/**
* Type conversions between arbitrary types and native `UA_*` types can be added.
* Conversions are handled by the TypeConverter struct. A new template specialization must be added
* to define a new conversion - this can happen outside of this library.
*
* In this case, we will enable conversion between the new C++17 type `std::byte` and `UA_Byte`.
*/
#include <array>
#include <cstddef> // byte, to_integer
#include <iostream>
namespace opcua {
template <>
struct TypeConverter<std::byte> {
using ValueType = std::byte;
using NativeType = UA_Byte;
// use `const NativeType& src` for non-primitive types
static void fromNative(NativeType src, ValueType& dst) {
dst = std::byte(src);
}
// use `const ValueType& src` for non-primitive types
static void toNative(ValueType src, NativeType& dst) {
dst = std::to_integer<UA_Byte>(src);
}
};
} // namespace opcua
int main() {
opcua::Variant variant;
// Write std::byte to variant
variant.setScalarCopy(std::byte{11});
// Read std::byte from variant (conversion requires copy)
const auto value = variant.getScalarCopy<std::byte>();
std::cout << "Byte value: " << std::to_integer<int>(value) << std::endl;
// Read UA_Byte from variant (zero copy possible)
const auto& valueNative = variant.getScalar<UA_Byte>();
std::cout << "Byte value: " << static_cast<int>(valueNative) << std::endl;
// Write array of bytes to variant
std::array<std::byte, 3> array{};
variant.setArrayCopy(array); // use array container
variant.setArrayCopy(opcua::Span{array.data(), array.size()}); // use raw array and size
variant.setArrayCopy(array.begin(), array.end()); // use iterator pair
std::cout << "Array size: " << variant.getArrayLength() << std::endl;
}
View to a contiguous sequence of objects, similar to std::span in C++20.
Definition span.hpp:26
constexpr pointer data() const noexcept
Definition span.hpp:109
UA_Variant wrapper class.
Definition types.hpp:887
T getScalarCopy() const
Get copy of scalar value with given template type.
Definition types.hpp:1050
void setArrayCopy(const ArrayLike &array)
Copy array to variant.
Definition types.hpp:1158
size_t getArrayLength() const noexcept
Get array length or 0 if variant is not an array.
Definition types.hpp:1056
void setScalarCopy(const T &value)
Copy scalar value to variant.
Definition types.hpp:1108
T & getScalar() &
Get reference to scalar value with given template type (only native or wrapper types).
Definition types.hpp:1019
uint8_t UA_Byte