Sunday, August 26, 2007

Type casting using Assembly code win32


We know that C++ will not allows assiging variable if they are on different typee. In That situations type casting is needed..But In some cases we can't use the c++ inbuilt type casting system as well as C style casting also..

 I am taking an exmaple of CreateThread thread proc function.(Beacuse many people uses static functions as the
thread proc for CreateThread.)

 For example if you look the function CreateThread API,the thread proc type is
DWORD WINAPI ThreadProc(void *lParam)
{

}

So this insist you to create some global functions or static functions.

Hence you can't pass your class member functions to CreateThread. So usually people will create some static functions and pass that function to CreateThread.And from inside that static function the appropriate class function is called..

This is fine. But using a littile asm code this can be avoided.
For example CCoffe is your class, and the MakeCoffe function we want to pass to CreateThread.  This can be done as below.

//sample codes
class CCoffe
{
  DWORD MakeCoffe(void *lParam)
  {
     return 0;
  }
}

//Initialization  function.
CCoffe::Init()
{  
   //temp is a function pointer of ThreadProc Type.
   DWORD (WINAPI*temp)(void*lp);
   __asm //Here we can pass any  address  to temp.      
   {


       mov EAX,CCoffe::MakeCoffe
       mov temp,EAX
   }
   //Call CreateThread with temp
   DWORD  out;
   CreateThread(0,0,temp,0,0,&out);
}

The Point is we can pass any address to temp,using asm block.Passing wrong function addresses 
may cause invalid stack structure,Might result in a crash.Hopes next time you will avoid static functions..

Note: I Don't know is this a good practice or not, If you have any opinion please let me know..


No comments: