Skip to main content
gamedev.net
🔒 Locked

C++ void pointer parameter

Started by discodowney Nov 10, 2011 at 2:51 PM 3 replies 1.6k views
Original Post
discodowney
discodowney
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?
SiCrane
SiCrane
The function makes an assumption about what the actual type is, makes an (in)appropriate cast and operates on cast type.
rip-off
rip-off
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.
Adam_42
Adam_42
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

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.