0

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.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
Alex Erwin
  • 333
  • 1
  • 10

1 Answers1

1

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.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • Is it my compiler then? When I attempted to use the same exact code to figure out the process the compiler complained bitterly that the definition of the function I was using only accepted apr_table_t*,const char*,const char*. I did not attempt to compile the code on windows but have done so on Linux many times. – Alex Erwin May 12 '12 at 23:29
  • @AlexErwin: Can you post some actual code, along with the error you are experiencing? – Kerrek SB May 12 '12 at 23:40
  • I am unsure how to do that on here because the code is plentiful. However a snippet of the structure of apr_table_t `struct apr_table_entry_t { char *key; char *val; apr_uint32_t key_checksum; };` I am not in a position to duplicate the error right at the moment, but when I perform this function `APR_DECLARE(void) apr_table_set(apr_table_t *t, const char *key, const char *val);` with a variable typed as void* the compiler balks and says that I am unable to do that. Could it be that it because I am using a C++ compiler? – Alex Erwin May 13 '12 at 00:07
  • @AlexErwin: Yes, it could. C and C++ are different languages. It's like translating an Italian source with a Spanish dictionary. – Kerrek SB May 13 '12 at 00:24