Explicit type casting in C++

1.5k views Asked by At

I am trying to convert a C code to C++. In my .c file I've definitions like this:

void services(void);
void transfers(void);

Further more, a thread will initialize the above two like this:

_beginthread((void*) services,0,NULL);
_beginthread((void*) transfers,0,NULL);

When I try to compile, I got the following error at both the places above like this:

Conversion from void* to pointer to non-void required an Explicit cast: Cannot convert parameter 1 from void* to void(_cdecl*)(void*)

I am confused about this, hope you guys make it clear for me :-)

3

There are 3 answers

5
nickie On BEST ANSWER

Try:

_beginthread((void(_cdecl*)(void*)) services, 0, NULL);

What you were doing was explicitly casting the function pointer to a non-function pointer type (void *). This was OK. But the _beginthread function expects as its first parameter a function pointer of the correct type mentioned in the error message. So you need to fix your cast.


If you're about to downvote this answer, I'd appreciate to know the reason why. I know it would be much better if user2754070 wanted to change the prototype of services (see my comments below). However, what I'm suggesting works (the answer was accepted) and, as far as I know, it is safe and standard practice in C libraries spawning threads. If you think it's not, please explain why and I'll consider deleting the answer.

0
liftarn On

It looks like you are trying to convert from C++ calling standard to C calling standard. cdecl stands for C declaration. To manually define a function to be cdecl you can use void _cdecl funct();

0
molbdnilo On

The solution is to use functions of the correct type and not cast them. Ignore the parameter if it's not relevant to the code.

void services(void*);
void transfers(void*);

_beginthread(services, 0, NULL);
_beginthread(transfers, 0, NULL);

If you absolutely can't change the functions, e.g. if you don't have access to the sources, use wrappers:

void correct_services(void*) { services(); }
_beginthread(correct_services, 0, NULL);

The compiler is helping you here - don't try to work around it by lying to it.