c++ - MFC 无法生成动态 DLL 文件

标签 c++ visual-studio-2010 dll mfc

我对 MFC DLL 有疑问。我使用 Visual Studio 2010。

这是我的动态链接库

#ifdef __cplusplus    // If used by C++ code, 
extern "C" {          // we need to export the C interface
#endif

    __declspec(dllexport) void __cdecl GetRAMInfo(DWORD& totaRamlPhysical, DWORD& availablephys, DWORD& memoload)
    {
        // Lay RAM
        MEMORYSTATUS status;
        status.dwLength = sizeof(status);
        GlobalMemoryStatus( &status ); // lay information of ram
        totaRamlPhysical = status.dwTotalPhys; // Tong dung luong RAM vat ly
        availablephys = status.dwAvailPhys; // Dung luong RAM vat ly dang duoc su dug
        memoload = status.dwMemoryLoad; // phan tram RAM duoc ca he thong su dung
    }

    __declspec(dllexport) void __cdecl GetCPUInfo(DWORD& processorArchitect, DWORD& typeProcessor, DWORD& numberProcessor)
    {
        SYSTEM_INFO siSysInfo; 
        GetSystemInfo(&siSysInfo); // lay thong tin cua CPU
        processorArchitect = siSysInfo.wProcessorArchitecture;
        numberProcessor = siSysInfo.dwNumberOfProcessors;
        typeProcessor = siSysInfo.dwProcessorType;
    }


    __declspec(dllexport) void __cdecl GetRAMuseandProcessMostUse(CString& namePMU, DWORD& ramUse)
    {
        //===========NAME PMU ==========//
        DWORD sizeallProcess; // Kich thuoc danh sach ID Process thu duoc
        DWORD processNumber; // So luong Process thu duoc
        DWORD arrayProcessID[100]; // mang chua danh sach ID Process
        EnumProcesses( arrayProcessID, sizeof(arrayProcessID), &sizeallProcess );  // lay danh sach process dang chay
        processNumber = sizeallProcess / sizeof(DWORD); // Lay so luong Process thu duoc
        namePMU = GetProcess(arrayProcessID, processNumber);
        ///===========RAM USE==============//
        DWORD arrayWorkingSetSize[100];
        unsigned int i;
        ramUse =0;
        for( i =0; i < processNumber;i++){
            HANDLE hProcess;
            PROCESS_MEMORY_COUNTERS pmc;

            hProcess = OpenProcess(  PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, arrayProcessID[i] ); // handle toi 1 process
            if (hProcess != NULL)
            {
                if ( GetProcessMemoryInfo( hProcess, &pmc, sizeof(pmc)) ){ // laays kich thuoc bo nho ma tien trinh do su dung
                    arrayWorkingSetSize[i] =  pmc.WorkingSetSize ;      
                }
            }           
            CloseHandle( hProcess );
        }
        for(i =2; i<(processNumber); i++){
            if(arrayWorkingSetSize[i] != 3435973836){
                ramUse += arrayWorkingSetSize[i];
            }
        }
    }

    __declspec(dllexport) void __cdecl GetCPUuseandProcessMostUse(CString& namePMUCPU, DOUBLE& cpuUse)
    {

        //DWORD processID = 2412;
        FILETIME ftSysIdle, ftSysKernel, ftSysUser;
        FILETIME ftProcCreation, ftProcExit, ftProcKernel, ftProcUser;
        //=== HANDLE of a PROCESS ==///

        DWORD sizeallProcess; // Kich thuoc danh sach ID Process thu duoc
        DWORD processNumber; // So luong Process thu duoc
        DWORD arrayProcessID[100]; // mang chua danh sach ID Process
        EnumProcesses( arrayProcessID, sizeof(arrayProcessID), &sizeallProcess );  // lay danh sach process dang chay
        processNumber = sizeallProcess / sizeof(DWORD); // Lay so luong Process thu duoc
        bool flagFor = FALSE;
        ULONGLONG arrayTotalSys[2][100];
        ULONGLONG arrayTotalProc[2][100];

        DOUBLE arrayPercent[100];
        for(unsigned int a = 0; a<2; a++) {     
            for(unsigned int i=2; i<processNumber; i++) {
                if(arrayProcessID[i] !=3435973836){
                    HANDLE hProcess;
                    hProcess = OpenProcess(  PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, arrayProcessID[i] );
                    GetSystemTimes(&ftSysIdle, &ftSysKernel, &ftSysUser);
                    GetProcessTimes(hProcess, &ftProcCreation, &ftProcExit, &ftProcKernel, &ftProcUser);
                    arrayTotalSys[a][i] = AddTimes(ftSysKernel, ftSysUser);
                    arrayTotalProc[a][i] = AddTimes(ftProcKernel, ftProcUser);
                }       

            }
            Sleep(500);
        }
        DOUBLE sumSys =0;
        DOUBLE sumProc =0;
        for(unsigned int i=2; i<processNumber; i++){
            if(arrayProcessID[i] !=3435973836){
                /*sumSys += arrayTotalSys[0][i] + arrayTotalSys[1][i];
                sumProc += arrayTotalProc[0][i] + arrayTotalProc[1][i];*/
                sumSys += arrayTotalSys[1][i] - arrayTotalSys[0][i] ;
                sumProc += arrayTotalProc[1][i] -  arrayTotalProc[0][i] ;
                arrayPercent[i] = (double)((100*sumProc)/sumSys);
            }
        }
        int maxindex = 2;
        double processMaxPercent = arrayPercent[2];
        double sumpercent =0;
        for(unsigned int i =2; i<(processNumber); i++){
            if(arrayPercent[i] != 3435973836){
                if(processMaxPercent < arrayPercent[i] ){
                    processMaxPercent = arrayPercent[i];
                    maxindex = i;
                }
                sumpercent += arrayPercent[i];
            }

        }

        cpuUse = sumpercent;
        namePMUCPU = GetNameProcessMU(arrayProcessID[maxindex]); // tam thoi lay ten mac djnh la cai nay
    }

    __declspec(dllexport) ULONGLONG __cdecl  AddTimes(const FILETIME& ftA,const FILETIME& ftB){
        LARGE_INTEGER a, b;
        a.LowPart = ftA.dwLowDateTime;
        a.HighPart = ftA.dwHighDateTime;

        b.LowPart = ftB.dwLowDateTime;
        b.HighPart = ftB.dwHighDateTime;
        return a.QuadPart + b.QuadPart;
    }
    __declspec(dllexport) CString  __cdecl GetProcess(DWORD arrayProcess[], DWORD numberprocess)
    {
        // Working set cua cac process
        DWORD arrayWorkingSetSize[100];
        unsigned int maxindex;
        DWORD processMaxSize;
        CString nameProcessMaxSize;
        unsigned int i;
        for( i =0; i < numberprocess;i++){
            HANDLE hProcess;
            PROCESS_MEMORY_COUNTERS pmc;

            hProcess = OpenProcess(  PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, arrayProcess[i] ); // handle toi 1 process
            if (hProcess != NULL)
            {
                if ( GetProcessMemoryInfo( hProcess, &pmc, sizeof(pmc)) ){ // laays kich thuoc bo nho ma tien trinh do su dung
                    arrayWorkingSetSize[i] =  pmc.WorkingSetSize ;      
                }
            }           
            CloseHandle( hProcess );
        }
        // Sap xep, lay ra phan tu co WorkingSetSize lon nhat 
        maxindex = 2;
        processMaxSize = arrayWorkingSetSize[2];
        for(i =2; i<(numberprocess - 10); i++){
            if(arrayWorkingSetSize[i] != 3435973836){
                if(processMaxSize < arrayWorkingSetSize[i] ){
                    processMaxSize = arrayWorkingSetSize[i];
                    maxindex = i;
                }
            }

        }

        // lay ten process co kich thuoc max
        nameProcessMaxSize = GetNameProcessMU(arrayProcess[maxindex]);

        return nameProcessMaxSize;
    }
    __declspec(dllexport) CString  __cdecl GetNameProcessMU(DWORD processID)
    {
        CString nameProcess;
        TCHAR szProcessName[MAX_PATH] = TEXT("<unknown>");
        HANDLE hProcess = OpenProcess( PROCESS_QUERY_INFORMATION |
            PROCESS_VM_READ,
            FALSE, processID );

        // Get the process name.
        if (NULL != hProcess )
        {
            HMODULE hMod;
            DWORD cbNeeded;

            if ( EnumProcessModules( hProcess, &hMod, sizeof(hMod), 
                &cbNeeded) )
            {
                GetModuleBaseName( hProcess, hMod, szProcessName, 
                    sizeof(szProcessName)/sizeof(TCHAR) );
            }
        }
        nameProcess = (LPCTSTR)szProcessName; // chuyen kieu
        CloseHandle( hProcess );
        return nameProcess;
    }

#ifdef __cplusplus
}
#endif

现在当我构建它时,它一次又一次地显示错误,注意到它不知道某些功能。

Error   1   error C3861: 'GetProcess': identifier not found c:\users\anhnt\documents\visual studio 2010\projects\bkav_btap2_dll\bkav_btap2_dll\bkav_btap2_dll.cpp   104 1   Bkav_btap2_dll
Error   2   error C3861: 'AddTimes': identifier not found   c:\users\anhnt\documents\visual studio 2010\projects\bkav_btap2_dll\bkav_btap2_dll\bkav_btap2_dll.cpp   154 1   Bkav_btap2_dll
Error   3   error C3861: 'AddTimes': identifier not found   c:\users\anhnt\documents\visual studio 2010\projects\bkav_btap2_dll\bkav_btap2_dll\bkav_btap2_dll.cpp   155 1   Bkav_btap2_dll
Error   4   error C3861: 'GetNameProcessMU': identifier not found   c:\users\anhnt\documents\visual studio 2010\projects\bkav_btap2_dll\bkav_btap2_dll\bkav_btap2_dll.cpp   187 1   Bkav_btap2_dll
Warning 5   warning C4190: 'GetProcess' has C-linkage specified, but returns UDT 'ATL::CStringT<BaseType,StringTraits>' which is incompatible with C    c:\users\anhnt\documents\visual studio 2010\projects\bkav_btap2_dll\bkav_btap2_dll\bkav_btap2_dll.cpp   200 1   Bkav_btap2_dll
Error   6   error C3861: 'GetNameProcessMU': identifier not found   c:\users\anhnt\documents\visual studio 2010\projects\bkav_btap2_dll\bkav_btap2_dll\bkav_btap2_dll.cpp   234 1   Bkav_btap2_dll
Warning 7   warning C4190: 'GetNameProcessMU' has C-linkage specified, but returns UDT 'ATL::CStringT<BaseType,StringTraits>' which is incompatible with C  c:\users\anhnt\documents\visual studio 2010\projects\bkav_btap2_dll\bkav_btap2_dll\bkav_btap2_dll.cpp   239 1   Bkav_btap2_dll

请帮助我 :(。谢谢

P/s:我阅读了这个主题 (stackoverflow.com/questions/17332327/cannot-build-dll-with-base-class) 但它对我不起作用。

最佳答案

您缺少包含所需库的头文件。将(至少)以下行添加到文件的开头:

#include <windows.h>

编辑:

如果我正在创建一个新的 Visual Studio 项目并将上面的代码粘贴到一个新文件中,如果我将以下行添加到源文件的顶部,它就会成功构建:

#include "stdafx.h" // Contains the afx default header files (which internally reference Windows.h)
#include <Psapi.h> // for process specific stuff

__declspec(dllexport) CString  __cdecl GetProcess(DWORD arrayProcess[], DWORD numberprocess);
__declspec(dllexport) ULONGLONG __cdecl  AddTimes(const FILETIME& ftA, const FILETIME& ftB);
__declspec(dllexport) CString  __cdecl GetNameProcessMU(DWORD processID);

此外,必须添加 psapi.lib 作为链接器输入。

我建议您阅读一些有关构建 C++ 项目、头文件和库的文档。您似乎缺少对 C++ 一些基本概念的理解。

编辑 2 以下是我的文件,它们构建良好。 (使用 MFC 项目向导时,任何丢失的文件都将保留原样,它们是可选的)

计算器.vcproj

<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <ItemGroup Label="ProjectConfigurations">
    <ProjectConfiguration Include="Debug|Win32">
      <Configuration>Debug</Configuration>
      <Platform>Win32</Platform>
    </ProjectConfiguration>
    <ProjectConfiguration Include="Release|Win32">
      <Configuration>Release</Configuration>
      <Platform>Win32</Platform>
    </ProjectConfiguration>
  </ItemGroup>
  <PropertyGroup Label="Globals">
    <ProjectGuid>{D25D3BF5-42FD-4649-BEE4-A7F142367727}</ProjectGuid>
    <RootNamespace>StackOverflow</RootNamespace>
    <Keyword>MFCDLLProj</Keyword>
  </PropertyGroup>
  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
    <ConfigurationType>DynamicLibrary</ConfigurationType>
    <UseDebugLibraries>true</UseDebugLibraries>
    <CharacterSet>Unicode</CharacterSet>
    <UseOfMfc>Dynamic</UseOfMfc>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
    <ConfigurationType>DynamicLibrary</ConfigurationType>
    <UseDebugLibraries>false</UseDebugLibraries>
    <WholeProgramOptimization>true</WholeProgramOptimization>
    <CharacterSet>Unicode</CharacterSet>
    <UseOfMfc>Dynamic</UseOfMfc>
  </PropertyGroup>
  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
  <ImportGroup Label="ExtensionSettings">
  </ImportGroup>
  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
  </ImportGroup>
  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
  </ImportGroup>
  <PropertyGroup Label="UserMacros" />
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
    <LinkIncremental>true</LinkIncremental>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
    <LinkIncremental>false</LinkIncremental>
  </PropertyGroup>
  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
    <ClCompile>
      <PrecompiledHeader>Use</PrecompiledHeader>
      <WarningLevel>Level3</WarningLevel>
      <Optimization>Disabled</Optimization>
      <PreprocessorDefinitions>SYSTEMINFO_LIB;WIN32;_WINDOWS;_DEBUG;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions>
    </ClCompile>
    <Link>
      <SubSystem>Windows</SubSystem>
      <GenerateDebugInformation>true</GenerateDebugInformation>
      <ModuleDefinitionFile>.\StackOverflow.def</ModuleDefinitionFile>
      <AdditionalDependencies>psapi.lib</AdditionalDependencies>
    </Link>
    <Midl>
      <MkTypLibCompatible>false</MkTypLibCompatible>
      <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
    </Midl>
    <ResourceCompile>
      <Culture>0x0407</Culture>
      <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
      <AdditionalIncludeDirectories>$(IntDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
    </ResourceCompile>
  </ItemDefinitionGroup>
  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
    <ClCompile>
      <WarningLevel>Level3</WarningLevel>
      <PrecompiledHeader>Use</PrecompiledHeader>
      <Optimization>MaxSpeed</Optimization>
      <FunctionLevelLinking>true</FunctionLevelLinking>
      <IntrinsicFunctions>true</IntrinsicFunctions>
      <PreprocessorDefinitions>SYSTEMINFO_LIB;WIN32;_WINDOWS;NDEBUG;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions>
    </ClCompile>
    <Link>
      <SubSystem>Windows</SubSystem>
      <GenerateDebugInformation>true</GenerateDebugInformation>
      <EnableCOMDATFolding>true</EnableCOMDATFolding>
      <OptimizeReferences>true</OptimizeReferences>
      <ModuleDefinitionFile>.\StackOverflow.def</ModuleDefinitionFile>
    </Link>
    <Midl>
      <MkTypLibCompatible>false</MkTypLibCompatible>
      <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
    </Midl>
    <ResourceCompile>
      <Culture>0x0407</Culture>
      <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
      <AdditionalIncludeDirectories>$(IntDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
    </ResourceCompile>
  </ItemDefinitionGroup>
  <ItemGroup>
    <None Include="ReadMe.txt" />
    <None Include="res\StackOverflow.rc2" />
    <None Include="StackOverflow.def" />
  </ItemGroup>
  <ItemGroup>
    <ClCompile Include="SystemInfo.cpp" />
    <ClCompile Include="StackOverflow.cpp" />
    <ClCompile Include="stdafx.cpp">
      <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Create</PrecompiledHeader>
      <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Create</PrecompiledHeader>
    </ClCompile>
  </ItemGroup>
  <ItemGroup>
    <ClInclude Include="Resource.h" />
    <ClInclude Include="StackOverflow.h" />
    <ClInclude Include="stdafx.h" />
    <ClInclude Include="SystemInfo.h" />
    <ClInclude Include="targetver.h" />
  </ItemGroup>
  <ItemGroup>
    <ResourceCompile Include="StackOverflow.rc" />
  </ItemGroup>
  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
  <ImportGroup Label="ExtensionTargets">
  </ImportGroup>
</Project>

计算器.vcproj.过滤器

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <ItemGroup>
    <Filter Include="Quelldateien">
      <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
    </Filter>
    <Filter Include="Headerdateien">
      <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
      <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
    </Filter>
    <Filter Include="Ressourcendateien">
      <UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
      <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
    </Filter>
  </ItemGroup>
  <ItemGroup>
    <None Include="ReadMe.txt" />
    <None Include="StackOverflow.def">
      <Filter>Quelldateien</Filter>
    </None>
    <None Include="res\StackOverflow.rc2">
      <Filter>Ressourcendateien</Filter>
    </None>
  </ItemGroup>
  <ItemGroup>
    <ClCompile Include="StackOverflow.cpp">
      <Filter>Quelldateien</Filter>
    </ClCompile>
    <ClCompile Include="stdafx.cpp">
      <Filter>Quelldateien</Filter>
    </ClCompile>
    <ClCompile Include="SystemInfo.cpp">
      <Filter>Quelldateien</Filter>
    </ClCompile>
  </ItemGroup>
  <ItemGroup>
    <ClInclude Include="StackOverflow.h">
      <Filter>Headerdateien</Filter>
    </ClInclude>
    <ClInclude Include="stdafx.h">
      <Filter>Headerdateien</Filter>
    </ClInclude>
    <ClInclude Include="targetver.h">
      <Filter>Headerdateien</Filter>
    </ClInclude>
    <ClInclude Include="Resource.h">
      <Filter>Headerdateien</Filter>
    </ClInclude>
    <ClInclude Include="SystemInfo.h">
      <Filter>Headerdateien</Filter>
    </ClInclude>
  </ItemGroup>
  <ItemGroup>
    <ResourceCompile Include="StackOverflow.rc">
      <Filter>Ressourcendateien</Filter>
    </ResourceCompile>
  </ItemGroup>
</Project>

系统信息.cpp

#include "stdafx.h"
#include <Psapi.h>
#include "SystemInfo.h"

SYSTEMINFO_EXPORTS void __cdecl GetRAMInfo(DWORD& totaRamlPhysical, DWORD& availablephys, DWORD& memoload)
{
    // Lay RAM
    MEMORYSTATUS status;
    status.dwLength = sizeof(status);
    GlobalMemoryStatus( &status ); // lay information of ram
    totaRamlPhysical = status.dwTotalPhys; // Tong dung luong RAM vat ly
    availablephys = status.dwAvailPhys; // Dung luong RAM vat ly dang duoc su dug
    memoload = status.dwMemoryLoad; // phan tram RAM duoc ca he thong su dung
}

SYSTEMINFO_EXPORTS void __cdecl GetCPUInfo(DWORD& processorArchitect, DWORD& typeProcessor, DWORD& numberProcessor)
{
    SYSTEM_INFO siSysInfo; 
    GetSystemInfo(&siSysInfo); // lay thong tin cua CPU
    processorArchitect = siSysInfo.wProcessorArchitecture;
    numberProcessor = siSysInfo.dwNumberOfProcessors;
    typeProcessor = siSysInfo.dwProcessorType;
}


SYSTEMINFO_EXPORTS void __cdecl GetRAMuseandProcessMostUse(CString& namePMU, DWORD& ramUse)
{
    //===========NAME PMU ==========//
    DWORD sizeallProcess; // Kich thuoc danh sach ID Process thu duoc
    DWORD processNumber; // So luong Process thu duoc
    DWORD arrayProcessID[100]; // mang chua danh sach ID Process
    EnumProcesses( arrayProcessID, sizeof(arrayProcessID), &sizeallProcess );  // lay danh sach process dang chay
    processNumber = sizeallProcess / sizeof(DWORD); // Lay so luong Process thu duoc
    namePMU = GetProcess(arrayProcessID, processNumber);
    ///===========RAM USE==============//
    DWORD arrayWorkingSetSize[100];
    unsigned int i;
    ramUse =0;
    for( i =0; i < processNumber;i++){
        HANDLE hProcess;
        PROCESS_MEMORY_COUNTERS pmc;

        hProcess = OpenProcess(  PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, arrayProcessID[i] ); // handle toi 1 process
        if (hProcess != NULL)
        {
            if ( GetProcessMemoryInfo( hProcess, &pmc, sizeof(pmc)) ){ // laays kich thuoc bo nho ma tien trinh do su dung
                arrayWorkingSetSize[i] =  pmc.WorkingSetSize ;      
            }
        }           
        CloseHandle( hProcess );
    }
    for(i =2; i<(processNumber); i++){
        if(arrayWorkingSetSize[i] != 3435973836){
            ramUse += arrayWorkingSetSize[i];
        }
    }
}

SYSTEMINFO_EXPORTS void __cdecl GetCPUuseandProcessMostUse(CString& namePMUCPU, DOUBLE& cpuUse)
{

    //DWORD processID = 2412;
    FILETIME ftSysIdle, ftSysKernel, ftSysUser;
    FILETIME ftProcCreation, ftProcExit, ftProcKernel, ftProcUser;
    //=== HANDLE of a PROCESS ==///

    DWORD sizeallProcess; // Kich thuoc danh sach ID Process thu duoc
    DWORD processNumber; // So luong Process thu duoc
    DWORD arrayProcessID[100]; // mang chua danh sach ID Process
    EnumProcesses( arrayProcessID, sizeof(arrayProcessID), &sizeallProcess );  // lay danh sach process dang chay
    processNumber = sizeallProcess / sizeof(DWORD); // Lay so luong Process thu duoc
    bool flagFor = FALSE;
    ULONGLONG arrayTotalSys[2][100];
    ULONGLONG arrayTotalProc[2][100];

    DOUBLE arrayPercent[100];
    for(unsigned int a = 0; a<2; a++) {     
        for(unsigned int i=2; i<processNumber; i++) {
            if(arrayProcessID[i] !=3435973836){
                HANDLE hProcess;
                hProcess = OpenProcess(  PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, arrayProcessID[i] );
                GetSystemTimes(&ftSysIdle, &ftSysKernel, &ftSysUser);
                GetProcessTimes(hProcess, &ftProcCreation, &ftProcExit, &ftProcKernel, &ftProcUser);
                arrayTotalSys[a][i] = AddTimes(ftSysKernel, ftSysUser);
                arrayTotalProc[a][i] = AddTimes(ftProcKernel, ftProcUser);
            }       

        }
        Sleep(500);
    }
    DOUBLE sumSys =0;
    DOUBLE sumProc =0;
    for(unsigned int i=2; i<processNumber; i++){
        if(arrayProcessID[i] !=3435973836){
            /*sumSys += arrayTotalSys[0][i] + arrayTotalSys[1][i];
            sumProc += arrayTotalProc[0][i] + arrayTotalProc[1][i];*/
            sumSys += arrayTotalSys[1][i] - arrayTotalSys[0][i] ;
            sumProc += arrayTotalProc[1][i] -  arrayTotalProc[0][i] ;
            arrayPercent[i] = (double)((100*sumProc)/sumSys);
        }
    }
    int maxindex = 2;
    double processMaxPercent = arrayPercent[2];
    double sumpercent =0;
    for(unsigned int i =2; i<(processNumber); i++){
        if(arrayPercent[i] != 3435973836){
            if(processMaxPercent < arrayPercent[i] ){
                processMaxPercent = arrayPercent[i];
                maxindex = i;
            }
            sumpercent += arrayPercent[i];
        }

    }

    cpuUse = sumpercent;
    namePMUCPU = GetNameProcessMU(arrayProcessID[maxindex]); // tam thoi lay ten mac djnh la cai nay
}

SYSTEMINFO_EXPORTS ULONGLONG __cdecl  AddTimes(const FILETIME& ftA,const FILETIME& ftB){
    LARGE_INTEGER a, b;
    a.LowPart = ftA.dwLowDateTime;
    a.HighPart = ftA.dwHighDateTime;

    b.LowPart = ftB.dwLowDateTime;
    b.HighPart = ftB.dwHighDateTime;
    return a.QuadPart + b.QuadPart;
}
SYSTEMINFO_EXPORTS CString  __cdecl GetProcess(DWORD arrayProcess[], DWORD numberprocess)
{
    // Working set cua cac process
    DWORD arrayWorkingSetSize[100];
    unsigned int maxindex;
    DWORD processMaxSize;
    CString nameProcessMaxSize;
    unsigned int i;
    for( i =0; i < numberprocess;i++){
        HANDLE hProcess;
        PROCESS_MEMORY_COUNTERS pmc;

        hProcess = OpenProcess(  PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, arrayProcess[i] ); // handle toi 1 process
        if (hProcess != NULL)
        {
            if ( GetProcessMemoryInfo( hProcess, &pmc, sizeof(pmc)) ){ // laays kich thuoc bo nho ma tien trinh do su dung
                arrayWorkingSetSize[i] =  pmc.WorkingSetSize ;      
            }
        }           
        CloseHandle( hProcess );
    }
    // Sap xep, lay ra phan tu co WorkingSetSize lon nhat 
    maxindex = 2;
    processMaxSize = arrayWorkingSetSize[2];
    for(i =2; i<(numberprocess - 10); i++){
        if(arrayWorkingSetSize[i] != 3435973836){
            if(processMaxSize < arrayWorkingSetSize[i] ){
                processMaxSize = arrayWorkingSetSize[i];
                maxindex = i;
            }
        }

    }

    // lay ten process co kich thuoc max
    nameProcessMaxSize = GetNameProcessMU(arrayProcess[maxindex]);

    return nameProcessMaxSize;
}

SYSTEMINFO_EXPORTS CString  __cdecl GetNameProcessMU(DWORD processID)
{
    CString nameProcess;
    TCHAR szProcessName[MAX_PATH] = TEXT("<unknown>");
    HANDLE hProcess = OpenProcess( PROCESS_QUERY_INFORMATION |
        PROCESS_VM_READ,
        FALSE, processID );

    // Get the process name.
    if (NULL != hProcess )
    {
        HMODULE hMod;
        DWORD cbNeeded;

        if ( EnumProcessModules( hProcess, &hMod, sizeof(hMod), 
            &cbNeeded) )
        {
            GetModuleBaseName( hProcess, hMod, szProcessName, 
                sizeof(szProcessName)/sizeof(TCHAR) );
        }
    }
    nameProcess = (LPCTSTR)szProcessName; // chuyen kieu
    CloseHandle( hProcess );
    return nameProcess;
}

系统信息.h

#pragma once
#include <Psapi.h>
SYSTEMINFO_EXPORTS CString  __cdecl GetProcess(DWORD arrayProcess[], DWORD numberprocess);

SYSTEMINFO_EXPORTS ULONGLONG __cdecl  AddTimes(const FILETIME& ftA, const FILETIME& ftB);

SYSTEMINFO_EXPORTS CString  __cdecl GetNameProcessMU(DWORD processID);

并将这些行添加到 stdafx.h:

#ifdef SYSTEMINFO_LIB
#define SYSTEMINFO_EXPORTS __declspec(dllexport)
#else 
#define SYSTEMINFO_EXPORTS __declspec(dllimport)
#endif

(哎呀,我希望我在这里发布这么多代码没有违反任何规则。)

关于c++ - MFC 无法生成动态 DLL 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24200258/

相关文章:

c++ - LPTSTR 只包含一个字母

Delphi:为什么我可以静态链接该函数但不能动态链接?

c++ - GLSL 纹理映射不起作用

c++ - 在 Windows 上使用 CMake 2.8.11 构建自定义 Qt 4.8.3 库时出错

c++ - 如何在调整窗口大小时调整 QListWidget 中项目的大小?

c# - VS2010实现通用接口(interface)扩展不使用指定类型

visual-studio - 默认情况下,如何在 Visual Studio XML 编辑器中打开 resx 文件?

asp.net - 允许预编译的 Visual Studio 网页可更新与不可更新之间有什么区别?

c++ - 如何在编译时验证reinterpret_cast的有效性

c++ - 套接字缓冲区中烦人的 NUL block