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..


Friday, August 24, 2007

NULL pointer and Some thoughts C++


Its me again , now came with a NULL pointer in hand... You may think what so special about NULL pointer , right ? .

it is very special . for example even if multiply two NULL pointers ,you will get a the result as a NULL pointer.. is it interesting ? .. :) I was just joking.. 

I wrote this beacause mostly people checks in destructor something like this

if(p) delete p;

 This is not needed , you can just avoid that checking, because delete NULL , will not cause any probles.
so if you have more pointers in your class to delete , avoid that checking is too good to see.

I think Now it is good to mention about this function  IsBadWritePtr . This function can be used to check
whether one address is good to write. In MFC there is function AfxIsValidAddress which will call this function to check.

The next thing about NULL pointer is that , You can still call member functions with null pointer, Like

CCLemon *p = NULL;

p->Drink() ;

Still this will works . but only one condition , Drink should not access any member variables of class CCLemon , and Drink shouldn't be a virtual function. If Drink is a virtual function result is Bhooommm!!!





Monday, August 20, 2007

Quick way to disable global keys (like ALT + TAB )


Some times it needed to disable the functonality of the global keys like ALT + TAB ,CTRL + ESC . For example when playing some games , pressing ALT + TAB will not cause to switch the tasks. Personaly i don't like this ,but programmers do these ,otherwise they might needed to handle something more..


So if you want to do these , One way is to use Hooks , using SetWindowHookEx api. But there is much simpler way to do this , using hot keys. There is function named RegisterHotKey , this will define a system wide hot key. So the effect is same as Hook.


After defining a hotkey ,when the hotkey is pressed by the user WM_HOTKEY message will be posted to message queue of that window .


So if you want to disable ALT+TAB , install a hotkey using
                                 RegisterHotKey(hwnd,id,MOD_ALT,VK_TAB).


  Done!!!! . Very simple than hooks.you can also handle the WM_HOTKEY message to do your own tasks..


Thursday, August 9, 2007

operator= & Inheritance c++


One interesting thing about operator = is that it can't be inherited.. So even if your base class has operator=  , no use for derived class. For example CString has operator= , but if you derive a class from CString you will not get = operator functionality in your derived class.

But there is a neat trick that will explicitly put this operator= in to the derived class. Here it is

class CString
{
public :
  CString& operator=(char *)
  {
     // some codes
     return *this;
  }
};
class CMyString : public CString
{
public:
  //We explicitly inserted the operator.
   using CString::operator=; 
};

Now CMyString gets the operator from CString.

Wednesday, August 8, 2007

Checking the presence of Virtual table in a class c++

The Last day when i am debugging one program , i saw the __vfptr symbol in VC++ . This represents the the vtable of a class. When you debuging your program try obj1.__vfptr in watch window. It will show the virtual functions of that class.

On that time I thought about writing such a function to check the vtable presence in a class , it is not a bad Idea..

So This post is about checking the whether a class contains virtual function or not. I want to write a function like IsVTablePresent(MYclass) , the function will return true if there is a vtable ,Otherwise false.

I don't know is this type of functins are really useful or not , but i think these are really smart Smile.

 Here is my solution using templates , It is very easy.

template <typename T>
class tDervVir : public T
{
 virtual void VirtualFun(){} //dummy
};


template <typename T>
class tDervNormal : public T
{
 // No virtual functions inside.
};


template <typename T>
class VFinder                  
{
 public :
 int IsVirtualContains() //this is our function
 {


     tDervNormal<T> obj1;
     tDervVir<T>    obj2;
     return sizeof(obj1) == sizeof(obj2);
 }


};

By using the above classes it can be done. For example consider a class CSample as the class for testing.


class CSample
{
   virtual void PoorMan(){}
};



We can check CSample as the following way

VFinder<CSample> tester;
(tester.IsVirtualContains() ? cout << "Virtual present" : cout << "Virtual not present" ;


Thats all for now..

Tuesday, August 7, 2007

Calling class Constructor C++

Some times we may think it would be nice , if we can call the constructor again for some initialization stuff (Normally constructor does the initialization job).  It is not possible to call the constructor of a class explicitly. Only way is to call is new operator. So here is that.

It is achived using placement new technique. it is very easy. For example if you have class CAlgoritham and the constructor of CAlgoritham does most of the initialization works. So after some processing you may want to  reset it to the old state (may be depnds on the algoritham). You have already wrote the initialization codes in constructor , but it is not possible to call constructor again. So we can use placement new. Here it is


CAlgoritham alg; //member variables Initialized already
alg.DoProces113();


new (&alg)CAlgoritham(); //this will call consructor again.But it  will not create a new memory (since we are giving memory location).


The statement new (&alg)CAlgoritham() is equal to CAlgoritham::CAlgoritham();

I like this kinda of things. Hopes you too. 

Saturday, August 4, 2007

STL Vector in VS 2005 ( when porting from 2003 or < )

In VS 2005 they changed almost all C runtime libraries and STL classes for adding security practices. Here is one information about the vector class in STL. So if you have any code written in 2003 , and if you port that to VS2005 be careful. 

In 2003 the following vector operations will work , like
vector<int> SomeInts;
SomeInte.push_back(0);
SomeInte.push_back(1);
SomeInte.push_back(2);


vector<int>::iterator it = SomeInts.Begin(); // Now it points to 0
++it;                                       // Now it points to 1
SomeInts.erase(it);                         // We are deleting the 1 from list
--it                                        // We want to move to 0 again.


and if you again ++it you will get 2. because we just deleted 1 from the vector. Ok, everything fine.
But In VS 2005 , the red marked line above(--it) cause to a crash!!! Open-mouthed. Because the iterator it is invalid so --it is also invalid.

 SO to correct that error best way is like this

vector<int> SomeInts;
SomeInte.push_back(0);
SomeInte.push_back(1);
SomeInte.push_back(2);
vector<int>::iterator it = SomeInts.Begin();   // Now it points to 0
++it;                                          // Now it points to 1
it = SomeInts.erase(it);                       // We are deleting the 1 from list
--it                                           // Now it points to 0


[ The last day , my friend told me he is getting a strange error in VS2005 , not in 2003, it was this problem. Smile]

Thursday, August 2, 2007

Calling Destructor & Virtual table c++

IF you really know how virtual functions work,it is really fun. Here is such an example(for fun i wrote a function fun  )

class base
{
public :
   virtual void fun()
   {
        cout <"base fun";
   }
  ~base(){}
};
class deriv: public base
{
    void fun()
    {
         cout << "deriv fun";
    }
   ~ deriv(){}
};

very simple two classes..
We know virtual funtions are initlaized in constructor and removed to their old base versions in the destructor.

Here is One more proof .
Try these if you are interested , otherwise go to www.youtube.com

base *p = new deiv();
p->fun();
p->~base();
p->fun();

the outputs will be first

deriv fun and
base fun

Because when we call p->~base() it will replaces the virtual pointer with the base version of fun. Thats why the base::fun get called.
We can't call constructor explicity as we did with destructor.
 Ok , I am stopping now.