Jump to content
  • Advertisement
Sign in to follow this  
discodowney

C++ void pointer parameter

This topic is 2587 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

So i have a piece of code like


function1(int param1, int param2, int param3, void *userData);


bool err = false;
Result res = function 1(x,y,z,&err)
....
.....
....

if(err == false)
...

Ive never seen this use of a void pointer parameter type. How does the function return a true or false to that parameter without knowing what type it is?

Share this post


Link to post
Share on other sites
Advertisement
The function makes an assumption about what the actual type is, makes an (in)appropriate cast and operates on cast type.

Share this post


Link to post
Share on other sites
Most userdata parameters are eventually passed back into your code at some time using a callback, or stored in a data structure that you can query later. Generally speaking, API's using void pointer userdata do not touch the value at all.

Share this post


Link to post
Share on other sites
It casts it back to something non-void - ideally a bool* in this case. Hopefully something no bigger than a bool, or it will trash memory. The function could look something like:

function1(int param1, int param2, int param3, void *userData)
{
*((bool*)userData) = false;
}


Of course normally you'd declare the function parameter type as bool* as it's less error prone. void* is usually only used when either the function wants to take a buffer holding any type (e.g. memcpy() takes void* parameters) or when the function is a callback and you don't know what type of parameter the user will want (e.g. CreateThread() takes a pointer to a function with a void* argument as well as a void* value to call that function with).

Edit: I type too slow :(

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!