In building a module for Apache web server, I have encountered several instances where the declaration of a structure says that it only takes const char*
members as in the declaration of apr_table_t
and apr_array_header_t
, but examples I am finding in various modules such as mod_security, and even the new ap_parse_form_data
function indicate that a void *
data type is being inserted into these structures.
My questions are how is this possible and why will my Visual Studio compiler complain if I attempt to use the same method?
A good example of this is mod_security with a create_request function that stores a void *
in a request_rec
note.
Pointers are convertible, and every object pointer type is convertible to void*
, in the sense that storing any pointer in a void*
doesn't lose information. That is to say, the following is valid:
struct Foo a;
struct Foo * p = &a; // p points to a
void * q = p; // OK, can store the value of p in q
struct Foo * r = q; // OK too - we can go back, and r points to a
r->n = 1;
Thus it is customary in C to pass around pointers as void*
, knowing that those can always hold any other object pointer value, and only cast it back to the desired type when needed.
One final word about char
pointers in particular: Casting any object pointer to char*
and actually dereferencing it as a pointer to an array of chars does not constitute type punning and is not a violation of the strict aliasing rule -- this simply allows you to access the underlying binary representation of any object.