October 21, 2024
Chicago 12, Melborne City, USA
C#

Write reusable pointer type casting logic in a function or macro


Here is the context of my question. I have this code :

typedef enum DType { float32 } DType;

typedef struct Array {
    void *data;
    DType dtype;
    ...
} Array;

The whole idea is to cast the pointer data to the adequate type depending on the value of the field dtype. Although it is possible to just switch on the dtype everytime it is needed, I would like to know if it’s possible to have a function / macro encapsulating that logic and usable anywhere needed.

To further illustrate, here is a non-solution I came up with :

void *cast_data_pointer(Array *arr) {
    switch (arr->dtype) {
        case float32:
            return (float *) arr->data;
        default:
            exit(1);
    }
}

Although the type casting logic is correct, it cannot be used because it requires to know in advance which pointer type will be returned :

Array arr = ...; # with dtype float32
void *data_ptr;

data_ptr = cast_data_pointer(&arr); # wrong because data_ptr is still a void pointer
Array arr = ...; # with dtype float32
float *data_ptr;

data_ptr = cast_data_pointer(&arr); # wrong because it required to know in advance that the function will return a float pointer

Having such a function / macro would avoid repetition as well as would be more flexible when I’ll add more dtypes to the DType enum in the future.

Thanks for your answers



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video