BackDoorNoBaby
BackDoorNoBaby

Reputation: 1455

Dynamic data type casting in C++

I am working on a DLL that uses a fixed set of 10 data types: unsigned/signed integers of 8/16/32/64-bit and floats of 32/64-bit.

I receive a void pointer to a buffer from the client along with an enum representing the data type. I then have to look at the data type enum supplied to know what data type to cast the buffer to in order to extract the value.

Example:

nU8Val  = (*(U8*)pvBuffer);
nU16Val = (*(U16*)pvBuffer);
nU32Val = (*(U32*)pvBuffer);

Is there any way to combine this logic into a single line such as:

nMyVal = *((TypeOf(nMyVal)*)pvBuffer);

Where I don't need to define variables for all data types and repeat the same logic for each data type enumeration

EDIT: I updated the example logic for clarity on what I was trying to do as far as casting the void* buffer to a pointer of the receiving variable's data type

Upvotes: 1

Views: 255

Answers (2)

Nick Mertin
Nick Mertin

Reputation: 1209

The problem here is that it's already in a dynamic type, namely void*. What I would do, if I understand your problem correctly, is create a struct with a void* (I would allocate a new block) and an enumeration value representing the data type. Then, use a switch statement to decide among very similar pieces of code when using the values. You can't simply cast everything to some 64-bit type such as double or unsigned long long, as is suggested in comments, because that could result in an unauthorized member l memory access error if the allocation is less than 8 bytes, which is quite conceivable, since 70% of the possible types are smaller than that.

Upvotes: 0

eerorika
eerorika

Reputation: 238351

Here's a template that can deduce the type from the assignee, so that you don't have to repeat it:

template<typename To>
void copy_deduced(void* from, To& to) {
    to = *reinterpret_cast<To*>(from); // avoid c-style casts
}
copy_deduced(pvBuffer, nU8Val);
// ...

Upvotes: 1

Related Questions