Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast to type known only at runtime

Tags:

c

ansi-c

let's say I have the following :

void *pA;

now I want at runtime to convert this pointer to a type that is not known at compile time. i.e. what is the equivalent or how to emulate in ANSI C a c++ dynamic_cast ?

Thanks !


2 Answers

now I want at runtime to convert this pointer to a type that is not known at compile time. i.e. what is the equivalent or how to emulate in ANSI C a c++ dynamic_cast ?

Well, that's not what dynamic_cast does. You cannot cast to a type which is not known at compile time.

If you need to cast the object to a type which may change during the execution of your program depending on various conditions then it can be as simple as creating a switch statement which checks some variable (and enumerated value, whatever) to determine which cast to perform. It can then work with the known type.


On a side note, it would be advantageous for you to describe your high level problem instead of how to implement your proposed solution (which may or may not make sense). There may exist alternatives to your approach which will be better than what you have envisioned, but we can't offer any without knowing what problem you are taking a stab at solving.

like image 151
Ed S. Avatar answered Oct 20 '25 17:10

Ed S.


Something like this might work:

void get_val(void * buf, void *data, int type_id) {
  switch (type_id) {
    case INT: int *sp = (int*)data;
              int *dp = (int*)buf;
              *dp = *sp; 
              // or just *((int*)buf) = *((int*)data)
              break;
    case FLOAT:float *sp = (float*)data;
               float *dp = (float*)buf;
               *dp = *sp; 
               break;
   /* ... */
  }
}
like image 25
perreal Avatar answered Oct 20 '25 19:10

perreal



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!