how to cast?

  • Thread starter =?ISO-8859-1?Q?Andreas_M=FCller?=
  • Start date
?

=?ISO-8859-1?Q?Andreas_M=FCller?=

i have a problem with threads and casts,
I created a thread
pthread_create(&grab_thread, NULL, grab_image, (void*)&camera);

and my function is like this:
void *grab_image(void *camera)
{..}

originally the type of camera is "struct Camera" but pthreads only wants
voids. now I need to cast the "void *camera" to "struct Camera *camera"
in the functions body. but how? or is the pthread_create wrong?
 
S

Srini

void *grab_image(void *parm)
{
Camera *camera = static_cast<Camera *>(parm);
// use camera
pthread_exit(0); // or whatever return value you might want
}

pthread_create(&thread_id, NULL, grab_image, (void *)(&camera));

HTH
Srini
 
E

Eric Lilja

Andreas Müller said:
i have a problem with threads and casts,
I created a thread
pthread_create(&grab_thread, NULL, grab_image, (void*)&camera);

and my function is like this:
void *grab_image(void *camera)
{..}

originally the type of camera is "struct Camera" but pthreads only wants
voids. now I need to cast the "void *camera" to "struct Camera *camera" in
the functions body. but how? or is the pthread_create wrong?

void * grab_image(void *arg) /* Note: renamed parameter)
{
Camera *my_camera = (Camera*)arg; /* Or appropriate C++-style cast */
}

Note, make sure you pass a pointer to an object of type Camera when you
create thread and make sure that pointer is still valid for the life-time of
the thread. And, btw, pthreads are not part of the C++ standard so next time
I suggest making an example program exhibiting your problem using standard
constructs only.

/ Eric
 
R

Ron Natalie

Andreas said:
i have a problem with threads and casts,
I created a thread
pthread_create(&grab_thread, NULL, grab_image, (void*)&camera);

and my function is like this:
void *grab_image(void *camera)
{..}

originally the type of camera is "struct Camera" but pthreads only wants
voids. now I need to cast the "void *camera" to "struct Camera *camera"
in the functions body. but how? or is the pthread_create wrong?

You don't need the void* cast above.
To cast it back:
void* v_camera = ...;

Camera* camera = static_cast<Camera*>(v_camera);
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top