Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dereferencing an array of void pointers

Tags:

c++

pointers

Say I have an array of void pointer pointing to objects of different types and I want to pass them through a function and cast them to pointers of their respective type, how would I go about doing this? I've tried this current code, but I get error:

‘void*’ is not a pointer-to-object type

objectA myObjectA;
objectB myObjectB;
objectC myObjectC;
objectD myObjectD;

void *data[4];

data[0] = static_cast<void *>( &myObjectA );
data[1] = static_cast<void *>( &myObjectB );
data[2] = static_cast<void *>( &myObjectC );
data[3] = static_cast<void *>( &myObjectD );

void dereference( void *data )
{
    objectA *objA_ptr = static_cast<objectA *>( data[0] );
    objectB *objB_ptr = static_cast<objectB *>( data[1] );
    objectC *objC_ptr = static_cast<objectC *>( data[2] );
    objectD *objD_ptr = static_cast<objectD *>( data[3] ); 
}

Anyone know the correct way to implement this?

edit: For context, I'm using opencv and trying to create a simple gui interface with a trackbar. Opencv allows for userdata to be fed into the TrackbarCallback which is called when the slider is moved, but only in the form of a void pointer.

 int createTrackbar( const string& trackbarname, const string& winname,
                           int* value, int count,
                           TrackbarCallback onChange=0,
                           void* userdata=0); 
like image 714
Matthew Yates Avatar asked Mar 09 '26 13:03

Matthew Yates


2 Answers

Say I have an array of void pointer

void deference( void *data )

That's not an array of void pointers, it's a single void pointer.

Change that to void **, and then since you're mixing C and C++ styles up anyway, why not just use a C style cast? :

objectA *objA_ptr = (objectA *) data[0];
like image 67
James McLaughlin Avatar answered Mar 12 '26 01:03

James McLaughlin


  1. Derive them all from the same base class.

  2. make the destructors virtual if your function needs to delete them.

  3. make your array BaseClass *data[4]

  4. make your function void deference(BaseClass **data)

like image 21
Not_a_Golfer Avatar answered Mar 12 '26 03:03

Not_a_Golfer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!