Variable Parameter Function forwarding of C, such as printf

Source: Internet
Author: User

Write a consoleProgramYou want to write a function to handle the output error information, as shown below:

 

Void exporterror (lpctstr perror );

 

Then print the information directly through printf.

 

Void exporterror (lpctstr perror)

{

Printf (perror );

}

 

Later, I thought this function was not convenient enough because we knew that printf supports variable parameters. This makes it easy to print some error messages, such

Printf ("error no: % d", 1 );

 

Then change your function to a variable parameter.

Void exporterror (...)

{

//???

}

 

However, we do not know how to pass the indefinite parameter to printf.

 

We know that VC ++ provides several macros that can pass variable parameters.

<Br/> tchar out [1024]; <br/> va_list body; <br/> va_start (body, FMT ); </P> <p> // but the function that receives the valist parameter must be used here, such as vsprintf, </P> <p> vsprintf (Out, FMT, body ); </P> <p> // After the output, you can find that the buffer is used as the buffer when the out parameter is added. What is the buffer size? Difficult to determine </P> <p> printf (out); <br/> va_end (body) ;}< br/>

 

So how can we directly pass variable parameters? If you are familiar with the C language structure, it is not difficult. We only need to provide a transition layer in the middle.

 

_ Declspec (naked) <br/> void _ cdecl exiterror (lpctstr perror ,...) <br/>{</P> <p> _ ASM <br/> {<br/> pop EBX <br/> call dword ptr [printf] <br/> push EBX <br/> RET <br/>}</P> <p >}< br/>

 

In this way, we first use Pop EBX to save the return address, and then call printf to pass the parameter directly, and then restore the address and return it. OK!

 

Debug and release are compiled.

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.