超级好用的C++实用库之跨平台实用方法

简介: 超级好用的C++实用库之跨平台实用方法

概述

C++跨平台开发时,我们经常会遇到一系列挑战和问题。这些问题主要源自不同操作系统和编译器之间的差异,这些差异包括但不限于以下几点。

1、不同的编译器(比如:GCC、Clang、MSVC等)对C++标准的支持程度和扩展特性存在差异,这可能导致同样的代码在不同平台上编译失败或行为不一致。

2、不同平台的系统头文件路径和库文件位置可能不同,需要通过条件编译或构建系统(比如:CMake)来进行适配。

3、Windows使用反斜杠\作为路径分隔符,而Unix-like系统使用正斜杠/。

4、不同平台的线程库和并发API有差异,这在前面的文章中已经提到过。

5、不同平台的内存对齐规则和字节序(大端或小端)可能不同,需要确保数据结构的定义和数据传输代码考虑到了这些差异。

6、动态库的命名规则、加载机制和依赖管理在不同平台上有差异,需要通过平台特定的配置来解决。

CHP_Utils

为了解决上面跨平台开发遇到的挑战和问题,我们封装了CHP_Utils类。CHP_Utils类是一个接口类,不需要实例化。因此,我们将构造函数和析构函数声明成了私有的,并提供了若干实用的静态函数。这些静态函数涵盖获取当前进程ID、获取当前线程ID、获取本地时间、获取CPU的使用率、获取内存的占用情况、获取网络的使用情况、获取磁盘目录的空间容量、字符串接口、文件路径接口等各种操作。

CHP_Utils类的头文件,可参考下面的示例代码。

#pragma once

#include <time.h>
#include <string>
#include <vector>
#include <map>

#ifdef _WIN32
        #include <WinSock2.h>
        #include <Pdh.h>
#endif

#include "HP_Types.h"
#include "HP_Mutex.h"
#include "HP_Socket.h"

#define HP_UTILS_MAX_PROCESSOR_COUNT     256

#ifndef MAX_PATH
        #define MAX_PATH                 260
#endif

#define HP_FILE_BSLASH_CHR              '\\'
#define HP_FILE_BSLASH_STR              "\\"
#define HP_FILE_SLASH_CHR               '/'
#define HP_FILE_SLASH_STR               "/"

#ifdef _WIN32
        #define HP_FILE_PATH_SEP_CHR   HP_FILE_BSLASH_CHR
        #define HP_FILE_PATH_SEP_STR   HP_FILE_BSLASH_STR
#else
        #define HP_FILE_PATH_SEP_CHR   HP_FILE_SLASH_CHR
        #define HP_FILE_PATH_SEP_STR   HP_FILE_SLASH_STR
#endif

class CHP_Utils
{
public:
        static int GetPID();

        static int GetThreadSelfID();

        static unsigned int GetCurTick();

        static int GetLastErrorCode();

        static int GetLocalTime(time_t tmTime, struct tm &tmLocal);

        static int GetGmTime(time_t tmTime, struct tm &tmGm);

        static int GetCPULoad(unsigned int &uiCPUCount, unsigned int &uiHighestLoad);

        static int GetMemoryLoad(unsigned int &uiTotalMemMB, unsigned int &uiAvailMemMB);

        static int GetNetworkLoad(unsigned int &uiDownloadBytePerSec, unsigned int &uiUploadBytePerSec, const char *pszInterface = "eth0");

        static int GetDiskSpace(const char *pszDiskDir, unsigned int &uiTotalMB, unsigned int &uiFreeMB);

        static int GetProcessCPULoad(unsigned int &uiCPULoad);

        static int GetProcessMemoryLoad(unsigned int &uiMemMB, unsigned int &uiVirMemMB);

        static void GetDiskSerialNumber(std::vector<std::string> &vctSerialNumber);

        static void Sleep(unsigned int uiTimeMs);

        static int StrCompareIgnoreCase(const char *pszText1, const char *pszText2);

        static int StrCompareIgnoreCase(const std::string &strText1, const std::string &strText2);

        static void StrToLower(char *pszText);

        static void StrToLower(std::string &strText);

        static void StrToUpper(char *pszText);

        static void StrToUpper(std::string &strText);

        static char *StrDequote(char *pszText);

        static void StrDequote(std::string &strText);

        static int StrTrim(char *pszText, const char cTrim = ' ');

        static int StrTrim(std::string &strText, const char cTrim = ' ');

        static void StrSplitByChar(const char *pszText, std::vector<std::string> &vctSubText, const char pszSplitChar[] = ";,", bool bTrim = true, bool bIgnoreBlank = false, bool bSupportQuote = false);

        static void StrSplitByStr(const char *pszText, std::vector<std::string> &vctSubText,
                const char *pszSplitStr, bool bTrim = true, bool bIgnoreBlank = false);

        static void StrGetAttribValue(const char *pszText, std::string &strAttr, std::string &strValue, bool bTrim = false, bool bDequote = false);

        static void StrGetAttribValueMap(const char *pszText, std::map<std::string, std::string> &mapAttrToVal, bool bTrim = false, bool bSupportQuote = false, bool bDequote = false, const char *pszSplitChar = " ;,");

        static char *HexStrToData(const char *pszHex, char *pData);

        static void HexStrToData(const std::string &strHexText, std::string &strData);

        static char *DataToHexStr(char *pData, int nDataLen, char *pszHexStr, bool bLowerCase = false, bool bWithPrefix0x = false);

        static void DataToHexStr(const std::string &strData, std::string &strHexText, bool bLowerCase = false, bool bWithPrefix0x = false);

        static bool StrMatched(const char *pszText, const char *pszPattern);

        static bool IsFileExist(const char *pszFile);

        static bool IsDirExist(const char *pszDir);

        static bool IsDirEmpty(const char *pszDir);

        static bool IsAbsolutePath(const char *pszPath);

        static bool IsPathEndWithSlash(const char *pszPath);

        static void NormalizePath(char pszPath[MAX_PATH], const char cSeparator = HP_FILE_PATH_SEP_CHR);

        static void NormalizePath(std::string &strPath, const char cSeparator = HP_FILE_PATH_SEP_CHR);

        static void AppendPath(char pszPath[MAX_PATH], const char *pszMore, 
                const char cSeparator = HP_FILE_PATH_SEP_CHR);

        static void AppendPath(std::string &strPath, const std::string &strMore,
                const char cSeparator = HP_FILE_PATH_SEP_CHR);

        static char *GetParentDirPath(char pszParentDirPath[MAX_PATH], const char *pszDirPath, const char cSeparator = HP_FILE_PATH_SEP_CHR);

        static void GetParentDirPath(std::string &strParentDirPath, const std::string &strDirPath, const char cSeparator = HP_FILE_PATH_SEP_CHR);

        static char *GetAppPathName(char pszPathName[MAX_PATH], HP_HANDLE hModule = NULL);

        static void GetAppPathName(std::string &strPathName, HP_HANDLE hModule = NULL);

        static char *GetAppOnlyPath(char pszPath[MAX_PATH], HP_HANDLE hModule = NULL);

        static void GetAppOnlyPath(std::string &strPath, HP_HANDLE hModule = NULL);

        static char *GetAppOnlyName(char pszName[MAX_PATH], HP_HANDLE hModule = NULL);

        static void GetAppOnlyName(std::string &strName, HP_HANDLE hModule = NULL);

        static char *PathNameToPath(char pszPath[MAX_PATH], const char *pszPathName,
                const char cSeparator = HP_FILE_PATH_SEP_CHR);

        static char *PathNameToName(char pszName[MAX_PATH], const char *pszPathName);

        static char *PathNameToNoExtName(char pszName[MAX_PATH], const char *pszPathName);

        static char *PathNameToExt(char pszExt[MAX_PATH], const char *pszPathName, bool bNoDot = true);

        static int UpdateTextFile(const char *pszFilePath, const char *pszText);

        static unsigned int Crc32(const unsigned char *pBuf, int nBufLen, unsigned int uiInitialCrc = 0);

        static int System(const char *pszCommand, bool bRunInBackgroundProcess = true);

        static int Fork(char *argv[], int &nPID, bool bRunInBackgroundProcess = true);

        static int WaitPID(int nPID, bool bRunInBackgroundProcess = true);

        static int GetPIDByCommand(const char *pszCommand, bool bExactlyMatch = false);

private:
        CHP_Utils();
        ~CHP_Utils();

        static bool StrMatchedInternal(const char *pszText, char *pszPattern);
        static bool IsQuanJiao(const char *pszText);
        static char *StrnCpy(char *pszDst, const char *pszSrc, size_t szLen);
        static void MakeCrcTable();
        static char CharToHex(char cValue);
        static bool IsCommandProcessExist(int nPID, const char *pszCommand);
        static bool ComposeForkData(char *argv[], char *pData, int &nDataLen);

private:
#ifdef _WIN32
        static HQUERY s_hQueryCPU;
        static HCOUNTER *s_pCounterCPU[HP_UTILS_MAX_PROCESSOR_COUNT];
        static HQUERY s_hQueryDownNetwork;
        static HQUERY s_hQueryUpNetwork;
        static std::vector<HCOUNTER *> s_vctCounterDownNetwork;
        static std::vector<HCOUNTER *> s_vctCounterUpNetwork;
        static HQUERY s_hQueryProcessCPU;
        static HQUERY s_hQueryProcessMem;
        static HQUERY s_hQueryProcessVirMem;
        static HCOUNTER *s_pCounterProcessCPU;
        static HCOUNTER *s_pCounterProcessMem;
        static HCOUNTER *s_pCounterProcessVirMem;
#else
        static float s_pfLastCPUIdle[HP_UTILS_MAX_PROCESSOR_COUNT];
        static unsigned int s_puiLastCPUTotal[HP_UTILS_MAX_PROCESSOR_COUNT];
        static unsigned int s_uiLastDownload;
        static unsigned int s_uiLastUpload;
        static unsigned int s_uiLastNetworkTick;
        static float s_fLastTotalTime;
        static float s_fLastProcessTime;
        static float s_fCurTotalTime;
        static float s_fCurProcessTime;

        static CHP_Mutex m_mutexDir;
        static HP_SOCKET m_sockBackgroundProcess;
        static CHP_Mutex m_mutexBackgroundProcess;
#endif

        static bool s_bCrcTableEmpty;
        static unsigned int s_puiCrcTable[256];
};

CHP_Utils类提供的公共接口有60个左右,这里就不一一介绍了。

总结

到这里,本专栏的所有内容就全部结束了。希望本专栏的内容能够帮助到各位大佬,有任何意见和问题,请在评论区反馈。最后,将这首写于2022年3月的拙词《蝶恋花》献给各位大佬。

已是晚春风微冷。片片残花,铺就满地粉。

今朝夏日应欢腾,却把来年春儿等。

 

已是中年近半生。颗颗雄心,化入水中沉。

功名利禄纵可能,最愿返璞又归真。

相关文章
|
18天前
|
API C++ Windows
Visual C++运行库、.NET Framework和DirectX运行库的作用及常见问题解决方案,涵盖MSVCP140.dll丢失、0xc000007b错误等典型故障的修复方法
本文介绍Visual C++运行库、.NET Framework和DirectX运行库的作用及常见问题解决方案,涵盖MSVCP140.dll丢失、0xc000007b错误等典型故障的修复方法,提供官方下载链接与系统修复工具使用指南。
344 2
|
21天前
|
Ubuntu API C++
C++标准库、Windows API及Ubuntu API的综合应用
总之,C++标准库、Windows API和Ubuntu API的综合应用是一项挑战性较大的任务,需要开发者具备跨平台编程的深入知识和丰富经验。通过合理的架构设计和有效的工具选择,可以在不同的操作系统平台上高效地开发和部署应用程序。
65 11
|
1月前
|
缓存 算法 程序员
C++STL底层原理:探秘标准模板库的内部机制
🌟蒋星熠Jaxonic带你深入STL底层:从容器内存管理到红黑树、哈希表,剖析迭代器、算法与分配器核心机制,揭秘C++标准库的高效设计哲学与性能优化实践。
C++STL底层原理:探秘标准模板库的内部机制
|
25天前
|
IDE 编译器 开发工具
msvcp100.dll,msvcp120.dll,msvcp140.dll,Microsoft Visual C++ 2015 Redistributable,Visual C++ 运行库安装
MSVC是Windows下C/C++开发核心工具,集成编译器、链接器与调试器,配合Visual Studio使用。其运行时库(如msvcp140.dll)为程序提供基础函数支持,常因缺失导致软件无法运行。通过安装对应版本的Microsoft Visual C++ Redistributable可解决此类问题,广泛应用于桌面软件、游戏及系统级开发。
220 2
|
2月前
|
存储 缓存 监控
用 C++ 红黑树给公司电脑监控软件的日志快速排序的方法
本文介绍基于C++红黑树算法实现公司监控电脑软件的日志高效管理,利用其自平衡特性提升日志排序、检索与动态更新效率,并结合实际场景提出优化方向,增强系统性能与稳定性。
69 4
|
2月前
|
并行计算 C++ Windows
|
9月前
|
编译器 C++ 开发者
【C++篇】深度解析类与对象(下)
在上一篇博客中,我们学习了C++的基础类与对象概念,包括类的定义、对象的使用和构造函数的作用。在这一篇,我们将深入探讨C++类的一些重要特性,如构造函数的高级用法、类型转换、static成员、友元、内部类、匿名对象,以及对象拷贝优化等。这些内容可以帮助你更好地理解和应用面向对象编程的核心理念,提升代码的健壮性、灵活性和可维护性。
|
5月前
|
人工智能 机器人 编译器
c++模板初阶----函数模板与类模板
class 类模板名private://类内成员声明class Apublic:A(T val):a(val){}private:T a;return 0;运行结果:注意:类模板中的成员函数若是放在类外定义时,需要加模板参数列表。return 0;
119 0
|
5月前
|
存储 编译器 程序员
c++的类(附含explicit关键字,友元,内部类)
本文介绍了C++中类的核心概念与用法,涵盖封装、继承、多态三大特性。重点讲解了类的定义(`class`与`struct`)、访问限定符(`private`、`public`、`protected`)、类的作用域及成员函数的声明与定义分离。同时深入探讨了类的大小计算、`this`指针、默认成员函数(构造函数、析构函数、拷贝构造、赋值重载)以及运算符重载等内容。 文章还详细分析了`explicit`关键字的作用、静态成员(变量与函数)、友元(友元函数与友元类)的概念及其使用场景,并简要介绍了内部类的特性。
206 0