Reputation: 161
I want to pass a variable by value (I used pointers only to avoid giving the parameter a type) into a function so that it can be used by another function contained within. The inner function can be given a variable of any type.
I have already tried using a generic pointer (void*) but it tells me that "'void*' is not a pointer-to-object type". I don't want to cast the pointer because the whole point of using a pointer is that it is generic.
void print_string(char *string, void *variable) {
Serial.print(string);
Serial.print(": ");
Serial.print(*variable); # This takes a variable of any type (int, float, double, char *);
Serial.println();
}
I want to be able to provide an int, double, float or string (char*).
Upvotes: 0
Views: 3625
Reputation: 3
You have to know the type, you could do something like:
enum DataType{
TYPE_FLOAT,
TYPE_U32,
TYPE_I32,
}
void print_string(char *string, void *variable, DataType type) {
Serial.print(string);
Serial.print(": ");
switch(type) {
case TYPE_I32:
Serial.print(*(int32_t *)variable);
break;
case TYPE_U32:
Serial.print(*(uint32_t *)variable);
break;
}
Serial.println();
}
uint32_t data = 1234;
print_string("hello", &data, TYPE_U32);
Upvotes: 0
Reputation: 1371
The answer is that you have to cast it despite not wanting to. You are trying to dereference a pointer which points to some memory location, but you aren't giving the compiler any semblance of what the size of that information is when it is void *
so it has no way of translating that to the proper assembly instruction for accessing that memory.
Upvotes: 3