Understanding Boost::any with function parameters, pointers, and proper casting

128 Views Asked by At

I have a fundamental understanding of using boost::any, but I've inherited some code that perplexes me. I am trying to understand the implementation and whether there is a better/correct way to implement.

Basically, I have a series of functions that will format int16, int32, string, or vector data used in conjunction with a serial interface that (1) writes program data out a serial interface, or (2) reads data from a serial interface into program memory.

For simplicity sake, I stripped things down. Here's main().

boost::any localData;
std::vector<uint8_t> serialBuffer(MAX_BUFFER_SIZE,0);

// First use:  read serial buffer: convert first four bytes to int32 
readSerialData(serialBuffer.data());
formatDataInt32(FROM_SERIAL, &localData, serialBuffer.data());

// :

//Second use: write to serial buffer: convert int32 to serial bytes
localData = (uint32_t)(0x11223344);
formatDataInt32(TO_SERIAL, &localData, serialBuffer.data());
writeSerialData(serialBuffer.data());

Here's a formatting function example:

void formatDataInt32(int direction, boost::any *plocal, uint8_t *pserial) {

if (direction == FROM_SERIAL) {
    // Looking for a solution using either of these instead of *plocal.
    //uint32_t *plocalInt32   = 
    //boost::any *pboostInt32 = 

    *plocal =  (uint32_t) ((pserial[0] << 24) | (pserial[1] << 16) | (pserial[2] << 8) | pserial[3]);
}

else if (direction == FROM_SERIAL) {
    ; // not worried about this implementation    
}

else {
    ; // unsupported
}}

This works at setting localData in the main program. . .

 *plocal =  (uint32_t) ((pserial[0] << 24) | (pserial[1] << 16) | (pserial[2] << 8) | pserial[3]);

But, can I accomplish the same thing using *plocalInt32, *pboostInt32, or something similar when casted using *pLocal? If so, how?

I've tried a range of syntaxes. I've gotten compile errors, 'boost::bad_any_cast' runtime errors, and flat out memory faults.

Using boost::any *pLocal as the second parameter just doesn't seem right. It seems like boost::any pLocal might be right.

Is there a problem with localData not being initialized with a 'dummy' value of the appropriate type? I thought I read about problems using boost::any_cast if a boost::any variable is not typed.

Is this a case (with risks) for using boost::unsafe_any_cast?

Using *plocal works. But, I want to better understand boost::any.

Thanks in advance, Striker.

0

There are 0 best solutions below