返回> 网站首页
vc++代码片段
yoours2014-03-28 16:48:25
简介一边听听音乐,一边写写文章。
1. 在窗口程序中输出信息到控制台
#include <io.h>
#include <fcntl.h>
void InitConsole()
{
int nRet= 0;
FILE* fp;
AllocConsole();
nRet= _open_osfhandle((long)GetStdHandle(STD_OUTPUT_HANDLE), _O_TEXT);
fp = _fdopen(nRet, "w");
*stdout = *fp;
setvbuf(stdout, NULL, _IONBF, 0);
}
//程序退出时调用
FreeConsole();
2. 编码转换
#include <locale.h>
#include <stdlib.h>
setlocale(LC_ALL,""); //要先设置语言环境
//Unicode to Anst
WCHAR wszStr = "Unicode String";
int nLength = wcstombs(NULL,(WCHAR*)lpBuffer,0) + 1; //得到要转换字符的个数
char* strBuffer = (char*)LocalAlloc(LPTR, nLength);
wcstombs(strBuffer,(WCHAR*)lpBuffer,nLength);
//Anst to Unicode
char szStr = "Ansi String";
int nLength = mbstowcs(NULL,(char*)lpBuffer,0) + 1; //得到要转换字符的个数
WCHAR* wcsBuffer = (WCHAR*)LocalAlloc(LPTR, nLength * sizeof(WCHAR));
mbstowcs(wcsBuffer,(char*)lpBuffer,nLength);
3. 精确计算时间差,可以精确到微秒
LARGE_INTEGER m_nFreq;
LARGE_INTEGER m_nBeginTime;
LARGE_INTEGER nEndTime;
QueryPerformanceFrequency(&m_nFreq); // 获取时钟周期
QueryPerformanceCounter(&m_nBeginTime); // 获取时钟计数
//Sleep(2);
QueryPerformanceCounter(&nEndTime);
int timeUsed = (nEndTime.QuadPart-m_nBeginTime.QuadPart)*1000/m_nFreq.QuadPart;
不使用GetTickCount是因为GetTickCount有误差。
4. WinCE注入
#include "stdafx.h"
#include <windows.h>
#include <commctrl.h>
#include <WinBase.h>
#include <Tlhelp32.h>
#pragma comment(lib,"toolhelp.lib")
TCHAR g_path[256]={0};
#pragma comment( linker, "/subsystem:\"windows\" /entry:\"mainCRTStartup\"" )
#define BYTE_BASE 1024000
//注入方式强制释放模块不再实现 有风险
DWORD WINAPI MyFree(LPVOID lParam)
{
HMODULE hh = (HMODULE)lParam;
FreeLibrary(hh);
return 0;
}
//此处没有细分wince下内存结构,只能查看组成模块所占用的空间信息,可查看模块的内存溢出状况(当New而未释放时模块内存会出现有规律的增加,可以查看每次增长字节数,另外可以查看存在的线程数量以及每个模块被调用次数----都可以在需要的时候自行添加)
void _tmain(int argc, _TCHAR* argv[])
{
HWND mWnd = ::FindWindow(_T("HHTaskBar"),NULL);
::ShowWindow(mWnd,SW_SHOWNORMAL);
wprintf(_T("回车键继续一次检查,输入任意字符点击回车键将退出\r\n程序将检查指定线程状态\r\n"));
while (TRUE)
{
Sleep(10);
/////////////////////////////////////////////////////////////
SYSTEM_INFO sysInfo;
GetSystemInfo(&sysInfo);
MEMORYSTATUS memstatus;
GlobalMemoryStatus(&memstatus);
wprintf(_T("MaximumApplicationAddress:0x%X MinimumApplicationAddress:0x%X MemoryUsing:%d% \r\n"),sysInfo.lpMaximumApplicationAddress,sysInfo.lpMinimumApplicationAddress,memstatus.dwMemoryLoad);
/////////////////////////////////////////////////////////////
UINT nProcessID = 0;
PROCESSENTRY32 pe = {sizeof(PROCESSENTRY32)};
MODULEENTRY32 me = {0};
DWORD dwSize = 0;
DWORD dwmodsize = 0;
HANDLE hSnapshot = ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS , 0);//所有进程快照
if (hSnapshot != INVALID_HANDLE_VALUE)
{
if (Process32First(hSnapshot, &pe))
{
do
{
//<1> 可以修改以查看不同程序的组成
if (lstrcmpi(_T("uss_main.exe"), pe.szExeFile) == 0)//名称可更改查看其他程序
{
nProcessID = pe.th32ProcessID;
HEAPLIST32 he={0};
he.dwSize = sizeof(HEAPLIST32);
HANDLE hSnapshot_heap = CreateToolhelp32Snapshot(TH32CS_SNAPHEAPLIST, nProcessID);
if (hSnapshot_heap != INVALID_HANDLE_VALUE)
{
if (Heap32ListFirst(hSnapshot_heap,&he))//进程堆栈结构信息
{
do
{
HANDLE h_heapentry = CreateToolhelp32Snapshot(TH32CS_SNAPHEAPLIST, nProcessID);
HEAPENTRY32 hee = {0};
hee.dwSize = sizeof(HEAPENTRY32);
if (h_heapentry != INVALID_HANDLE_VALUE)
{
if (Heap32First(h_heapentry,&hee,he.th32ProcessID,he.th32HeapID))
{
do
{
dwSize+=hee.dwBlockSize;
} while (Heap32Next(h_heapentry,&hee));
}
::CloseToolhelp32Snapshot(h_heapentry);//必须关掉 否则溢出
}
} while (Heap32ListNext(hSnapshot_heap,&he));
}
::CloseToolhelp32Snapshot(hSnapshot_heap);//必须关掉 否则溢出
}
/*
此处也可以获取他们的内存信息 使用 virtualQuery可以了解 空闲、提交、占用的内存信息
地址由提供的地址+0X400 开始 每次query MEMORY_BASIC_INFOMATION个结构大小
另外更方便的virtualQueryEx在ce下无法使用
OpenProcess之后使用virtualAlloc等注入比较困难,似乎需要用到安全令牌,不再考虑(仅wince下有困难)
*/
//属于此进程的包含模块信息
me.dwSize = sizeof(MODULEENTRY32);
HANDLE hSnapshot1 = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, nProcessID);
if (hSnapshot1 == INVALID_HANDLE_VALUE)
{
break;
}
//<2> 可屏蔽下列具体模块名称 完全显示对应<1>的所有模块信息
if (::Module32First(hSnapshot1,&me))//模块结构信息
{
do
{
//可以添加新的模块
//
if (lstrcmpi(_T("uss_cali.dll"), me.szModule) == 0)
{
dwmodsize+=me.modBaseSize;
wprintf(_T("Process:%s PID:%d ThreadCount:%d ProcessMem:%.5f Module:%s ModuleAddr:0x%X GUsage:%d PUsage:%d ModuleSize:%.5f \r\n"),pe.szExeFile,pe.th32ProcessID,pe.cntThreads,(double)dwSize/BYTE_BASE,me.szModule,me.modBaseAddr,me.GlblcntUsage,me.ProccntUsage,(double)me.modBaseSize/BYTE_BASE);
}
} while (::Module32Next(hSnapshot1,&me));
}
::CloseToolhelp32Snapshot(hSnapshot1);
//break;
}
}while (Process32Next(hSnapshot, &pe));
}
::CloseToolhelp32Snapshot(hSnapshot);
DWORD dws = dwSize - dwmodsize;
wprintf(_T("BaseModuleMem:%.5f StoreMem:%.5f TotalMem:%.5f system-dll&exe:(...)\r\n"),(double)dwmodsize/BYTE_BASE,(double)dws/BYTE_BASE,(double)dwSize/BYTE_BASE);
}
int xx = getchar();
if (xx != 10)
{
break;
}
else
continue;
}
}
5. 在windows窗口程序中输出信息到控制台
#ifdef WIN32
#ifdef NDEBUG
#pragma comment(linker,"/subsystem:Windows /entry:mainCRTStartup")
#else
#pragma comment(linker,"/subsystem:console /nodefaultlib:libc")
#endif // NDEBUG
#endif // WIN32
6. 计时
#pragma warning(push)
#pragma warning( disable : 4710 )
class CTimeCounter
{
public:
CTimeCounter(void)
{
QueryPerformanceFrequency(&m_nFreq);
QueryPerformanceCounter(&m_nBeginTime);
}
virtual ~CTimeCounter(void)
{
}
__int64 GetExecutionTime()
{
LARGE_INTEGER nEndTime;
__int64 nCalcTime;
QueryPerformanceCounter(&nEndTime);
nCalcTime = (nEndTime.QuadPart - m_nBeginTime.QuadPart) *
1000/m_nFreq.QuadPart;
delete this;
return nCalcTime;
}
protected:
LARGE_INTEGER m_nFreq;
LARGE_INTEGER m_nBeginTime;
};
#pragma warning(pop)
7. 快速清零
void *memzero(void *const mem, const size_t n)
{
size_t i, j, offset;
unsigned long long *q;
const unsigned long long qzero = 0ULL;
unsigned char *b;
const unsigned char bzero = 0U;
assert(mem != NULL);
assert(n > 0);
i = 0;
if (n-i >= 2*sizeof(qzero)) {
b = (unsigned char*)mem;
offset = 8;
offset -= (size_t) b % sizeof(qzero);
switch (offset) {
case 7: *b = bzero; b++; i++;
case 6: *b = bzero; b++; i++;
case 5: *b = bzero; b++; i++;
case 4: *b = bzero; b++; i++;
case 3: *b = bzero; b++; i++;
case 2: *b = bzero; b++; i++;
case 1: *b = bzero; b++; i++;
case 0: break;
}
q = (unsigned long long *) b;
q[0] = qzero;
for (j = 1; j < (n-i)/sizeof(qzero); j++) {
q[j] = q[j-1];
}
i += j*sizeof(qzero);
}
if (i >= n) {
return mem;
}
b = (unsigned char*)mem;
b += i;
b[0] = bzero;
for (j = 1; j < n-i; j++) {
b[j] = b[j-1];
}
return mem;
}
8. 快速拷贝内存
void *memcpy_optimized(void *dst, const void *src, size_t sz)
{
void *r = dst;
//先进行uint64_t长度的拷贝,一般而言,内存地址都是对齐的,
size_t n = sz & ~(sizeof(uint64_t) - 1);
uint64_t *src_u64 = (uint64_t *) src;
uint64_t *dst_u64 = (uint64_t *) dst;
while (n)
{
*dst_u64++ = *src_u64++;
n -= sizeof(uint64_t);
}
//将没有非8字节字长取整的部分copy
n = sz & (sizeof(uint64_t) - 1);
byte *src_u8 = (byte *) src;
byte *dst_u8 = (byte *) dst;
while (n-- )
{
(*dst_u8++ = *src_u8++);
}
return r;
return NULL;
}
9. 打开资源管理器,定位文件的位置
CString filename = pJobObj->GetFilePath();
ShellExecute(NULL, NULL,_T("explorer"), _T("/select, ")+filename, NULL,SW_SHOW);
10. 退出指定程序
#include <Tlhelp32.h>
//#define WINCE_HD //CE 平台
#ifdef WINCE_HD
#pragma comment(lib,"Toolhelp.lib");
#endif //#ifdef WINCE_HD
BOOL ProcessExist(LPCTSTR lpsz)
{
CString strExeName(lpsz);
strExeName.MakeLower();
HANDLE handle=::CreateToolhelp32Snapshot(TH32CS_SNAPALL,0);
PROCESSENTRY32* Info = new PROCESSENTRY32;
Info->dwSize = sizeof(PROCESSENTRY32);
if(::Process32First(handle,Info))
{
while(::Process32Next(handle,Info)!=FALSE)
{
CString ss;
ss=Info->szExeFile;
ss.MakeLower();
if(ss.Compare(strExeName) == 0)
{
delete Info;
#ifdef WINCE_HD
CloseToolhelp32Snapshot(handle);
#else
CloseHandle(handle);
#endif
return TRUE;
}
}
if(Info)
{
delete Info;
}
#ifdef WINCE_HD
CloseToolhelp32Snapshot(handle);
#else
CloseHandle(handle);
#endif
return FALSE;
}
}
11. 综合
class CHelper
{
public:
static tstring GetModulePath(TCHAR* filename = NULL);
static tstring GetModuleName();
static HMODULE LoadDll(TCHAR* name, bool bWarn = true/*加载失败是否提示*/);
static string& TrimLeft(string& str, char ch);
static string& TrimRight(string& str, char ch);
static string& Trim(string& str, char ch);
static vector<string> Split(string& str, char ch);
static bool Utf2Unicode(string& utf8, wstring& unicode);
static bool Unicode2Ascii(wstring& unicode, string& ascii);
static bool Utf2Ascii(string &utf, string &ascii);
static bool Ascii2Unicode(string& ascii, wstring& unicode);
static bool Unicode2Utf(wstring &unicode, string &utf);
static bool Ascii2Utf(string &ascii, string &utf);
static bool IsNumber(const char *str);
static bool IsIpAddress(const char *ipstr);
};
cpp文件
#include <windows.h>
#include "Helper.h"
#include <regex>
#include <algorithm>
tstring CHelper::GetModulePath(TCHAR *fileName)
{
TCHAR cpath[MAX_PATH + 1] = {0};
HMODULE hModule;
void *callerAddress = _ReturnAddress();
GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (LPCTSTR)callerAddress, &hModule);
GetModuleFileName(hModule, cpath, sizeof(cpath)/sizeof(TCHAR));
tstring spath = cpath;
int pos = spath.find_last_of('\\');
spath = spath.substr(0, pos + 1);
return fileName == NULL? spath: spath + fileName;
}
tstring CHelper::GetModuleName()
{
TCHAR cpath[MAX_PATH + 1] = {0};
HMODULE hModule;
void *callerAddress = _ReturnAddress();
GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (LPCTSTR)callerAddress, &hModule);
GetModuleFileName(hModule, cpath, sizeof(cpath)/(sizeof(TCHAR)));
tstring spath = cpath;
int pos = spath.find_last_of('\\');
spath = spath.substr(pos + 1);
return spath;
}
HMODULE CHelper::LoadDll(TCHAR* name, bool bWarn)
{
HMODULE hDll = ::LoadLibrary(GetModulePath(name).c_str());
if (hDll == NULL && bWarn)
{
tstring msg = _T("加载Dll “") + GetModulePath(name) + _T("” 失败,请检查该文件是否存在!");
::MessageBox(NULL, msg.c_str(), _T("加载Dll失败"), MB_OK);
}
return hDll;
}
string& CHelper::TrimLeft(string& str, char ch)
{
int pos = 0;
for (pos = 0; pos < (int)str.size(); pos++)
{
if (str.at(pos) != ch) break;
}
str = str.substr(pos);
return str;
}
string& CHelper::TrimRight(string& str, char ch)
{
vector<char> chs;
int pos = str.size() - 1;
for (pos; pos >= 0; pos--)
{
if (str.at(pos) != ch) break;
}
str.resize(pos + 1);
return str;
}
string& CHelper::Trim(string& str, char ch)
{
return TrimLeft(TrimRight(str, ch), ch);
}
vector<string> CHelper::Split(string& str, char ch)
{
vector<string> sp_strs;
Trim(str, ch);
string::size_type s_p = 0, e_p = 0;
while (e_p != string::npos && e_p != str.length())
{
e_p = str.find_first_of(ch, s_p);
if (e_p == string::npos) e_p = str.length();
sp_strs.push_back(str.substr(s_p, e_p - s_p));
s_p = e_p + 1;
}
return sp_strs;
}
bool CHelper::Utf2Unicode(string& utf8, wstring& unicode)
{
int wideSize = ::MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), -1, NULL, 0);
if (wideSize == ERROR_NO_UNICODE_TRANSLATION)
return false;
if (wideSize == 0)
return false;
vector<wchar_t> resultString(wideSize);
int convResult = ::MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), -1, &resultString[0], wideSize);
if (convResult != wideSize)
return false;
unicode = wstring(&resultString[0]);
return true;
}
bool CHelper::Unicode2Ascii(wstring& unicode, string& ascii)
{
int asciiSize = ::WideCharToMultiByte(CP_OEMCP, 0, unicode.c_str(), -1, NULL, 0, NULL, NULL);
if (asciiSize == ERROR_NO_UNICODE_TRANSLATION)
return false;
if (asciiSize == 0)
return false;
vector<char> resultString(asciiSize);
int convResult = ::WideCharToMultiByte(CP_OEMCP, 0, unicode.c_str(), -1, &resultString[0], asciiSize, NULL, NULL);
if (convResult != asciiSize) return false;
ascii = string(&resultString[0]);
return true;
}
bool CHelper::Utf2Ascii(string &utf, string &ascii)
{
wstring wstr;
bool res;
res = Utf2Unicode(utf, wstr);
if (!res) return false;
res = Unicode2Ascii(wstr, ascii);
if (!res) return false;
return true;
}
bool CHelper::Ascii2Unicode(string& ascii, wstring& unicode)
{
int wideSize = MultiByteToWideChar(CP_ACP, 0, (char *)ascii.c_str(), -1, NULL, 0);
if (wideSize == ERROR_NO_UNICODE_TRANSLATION)
return false;
if (wideSize == 0)
return false;
vector<wchar_t> resultString(wideSize);
int conResult = MultiByteToWideChar(CP_ACP, 0, (char *)ascii.c_str(), -1, &resultString[0], wideSize);
if (conResult != wideSize)
return false;
unicode = wstring(&resultString[0]);
return true;
}
bool CHelper::Unicode2Utf(wstring &unicode, string &utf)
{
int utfSize = WideCharToMultiByte(CP_UTF8, 0, unicode.c_str(), -1, NULL, 0, NULL, NULL);
if (utfSize == 0)
return false;
vector<char> resultString(utfSize);
int conResult = WideCharToMultiByte(CP_UTF8, 0, unicode.c_str(), -1, &resultString[0], utfSize, NULL, NULL);
if (conResult == utfSize)
return false;
utf = string(&resultString[0]);
return true;
}
bool CHelper::Ascii2Utf(string &ascii, string &utf)
{
wstring unicode;
bool res;
res = Ascii2Unicode(ascii, unicode);
if (res == false) return false;
res = Unicode2Utf(unicode, utf);
if (res == false) return false;
return true;
}
bool CHelper::IsNumber(const char *str)
{
if (str == NULL) return false;
while (*str++ != '\0')
{
if (*str < '0' || *str > '9') return false;
}
return true;
}
bool CHelper::IsIpAddress(const char *ipstr)
{
if (ipstr == NULL) return false;
regex ipPattern("(\\d{1,3}.){3}(\\d{1,3})");
return regex_match(ipstr, ipPattern);
}
12. 编译时间
const TCHAR BuildTime::DATE[] = _T(__DATE__) _T(" at ") _T(__TIME__);
文章评论
1603人参与,0条评论