Use the class's member function as the callback function for the API timer

Source: Internet
Author: User

Sometimes, when we use the API timer, we need to use the class's member function as its callback function, but the compiler cannot pass the compiler in order to protect the member function. So how can we use the class's member function as the callback function of the API timer? We can embed a piece of assembler code to bypass the compiler's checks. As an example:

Assuming that our member function for a class is defined as void CALLBACK EXPORT Ctestdlg::timerproc, then when we use the API timer, it is compiled if we write it directly:

:: SetTimer (M_hwnd,1,1000,timerproc);

The workaround for embedding a piece of assembler code is as follows:

Timerproc tproc;__asm{mov eax,timerproc//timerproc function address into EAX Register MOV tproc,eax//Assign value in EAX register to Tproc}::s Ettimer (M_HWND,1,1000,TPROC);

By doing this, we can compile, but doing so will create a problem when entering the Timerproc function body and discovering that the this pointer is empty, and calling the function this pointer directly is normal. To solve this problem, we can define a global pointer variable pthis, which is used to globally save the this pointer. The member variables and member functions of the class are then accessed using the Pthis pointer in the TIMERPROC function body. Or use a piece of assembly code at the beginning of the function to correct the this pointer:

__asm{mov ecx,pthis//register ECX used to hold the address of this pointer mov this,ecx}

The above procedure solves the problem of using the class's member function as the callback function of the API timer, which is not recommended in programming (there are many alternatives).

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.