传递格式化的参数给另外一个函数
// ValistToFunction.cpp : Defines the entry point for the console application.
//
//功能: 传递格式化的参数给另外一个函数
#include "stdafx.h"
#include <windows.h>
#include <stdlib.h>
#include <stdio.h>
#include <crtdbg.h>
#include <tchar.h>
#define G_INT_MSG_BUF_SIZE (int)2048
int MyPrintf(TCHAR * szFormat);
int MyPrintfV(TCHAR * szFormat, ...);
int main(int argc, char* argv[])
{
MyPrintfV(_T("[%s] 整理: %d/%d/%d %d:%d"),
"传递格式化的参数给另外一个函数",
2010, 06, 06, 16, 28);
printf("END/n");
getchar();
return 0;
}
/// 字符串格式化时, 依赖定长Buffer不好
/// 见本文目录 <<计算变长字符串入参的最大长度>>
int MyPrintfV(TCHAR * szFormat, ...)
{//入参为格式化的参数列表
va_list args;
va_start(args, szFormat);
PTCHAR pBufMsg = new TCHAR[G_INT_MSG_BUF_SIZE];
_ASSERT(pBufMsg);
memset(pBufMsg, 0, G_INT_MSG_BUF_SIZE);
int nRc = 0;
nRc = _vsntprintf(pBufMsg, G_INT_MSG_BUF_SIZE, szFormat, args);
_ASSERT(G_INT_MSG_BUF_SIZE > nRc);
va_end(args);
MyPrintf(pBufMsg);
delete pBufMsg;
pBufMsg = NULL;
return S_OK;
}
int MyPrintf(TCHAR * szFormat)
{//入参为单一字符串
//这里是打印, 换成别的任务, 就是命令行分析, 执行命令行制定的任务
printf("%s/n", szFormat);
return S_OK;
}
<2010_1219>
得到函数列表中的每个参数, 这里假设每个参数都是串, 如果是别的类型,也当串来解析,然后强转一下.
传可变参数列表给函数, 适用于用户调用函数,这样方便。
在函数内部如果需要把参数列表,再传给内部函数之前,把参数先解析出来保存好,
效率比再把参数列表复制一份传给内部函数的方法效率高.
<2013_0812>
计算变长字符串入参的最大长度
std::wstring StringFormatV(wchar_t * szFormat, ...)
{//入参为格式化的参数列表
size_t nStrLen = 0;
wchar_t * pBufMsg = NULL;
std::wstring strRc;
va_list args;
va_start(args, szFormat);
nStrLen = _vsntprintf(NULL, 0, szFormat, args);
pBufMsg = new wchar_t[nStrLen + 1];
_ASSERT(pBufMsg);
::ZeroMemory(pBufMsg, (nStrLen + 1) * sizeof(wchar_t));
nStrLen = _vsntprintf(pBufMsg, nStrLen, szFormat, args);
va_end(args);
strRc = pBufMsg;
delete []pBufMsg;
pBufMsg = NULL;
return strRc;
}