虚拟内存示例代码 WinApi C++ [英] Virtual Memory Sample code WinApi C++

查看:37
本文介绍了虚拟内存示例代码 WinApi C++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于内存分配的教程代码有一些问题.下面有一个代码可以做到:1) 打印虚拟内存数据2)内存分配3) 打印虚拟内存数据4)内存释放5) 打印虚拟内存数据

I have some problems with tutorial code about Memory allocation. Below there is a code which do: 1) print virtal memory data 2) memory allocation 3) print virtal memory data 4) memory releasing 5) print virtal memory data

我才刚开始学习 WinApi 的 C++.有人可以帮我写代码吗?我无法编译它.我遇到了一些错误(如下所示).据我所知,此代码在 MS Visual Studio 的早期版本中正常工作.目前我正在使用 2010 版本.提前致谢.

I am only starting learning C++ for WinApi. Can somebody help me with code? I cannot compile it.I am getting some errors(are shown below). As I know this code worked correctly in earlier versions of MS Visual Studio. Currently I am working with 2010 version. Thanks in advance.

 #include "stdafx.h"

LPVOID myblock[5];
BOOL alloc = FALSE;

PCTSTR GetProtectText(MEMORY_BASIC_INFORMATION mbi)
{
    PCTSTR p = "Unknown";
    if(mbi.State == MEM_FREE) mbi.Protect = PAGE_NOACCESS;
    if(mbi.State == MEM_RESERVE) mbi.Protect = mbi.AllocationProtect;
    switch (mbi.Protect & ~(PAGE_GUARD | PAGE_NOCACHE | PAGE_WRITECOMBINE))
    {
        case PAGE_READONLY:          p = "-R--"; break;
        case PAGE_READWRITE:         p = "-RW-"; break;
        case PAGE_WRITECOPY:         p = "-RWC"; break;
        case PAGE_EXECUTE:           p = "E---"; break;
        case PAGE_EXECUTE_READ:      p = "ER--"; break;
        case PAGE_EXECUTE_READWRITE: p = "ERW-"; break;
        case PAGE_EXECUTE_WRITECOPY: p = "ERWC"; break;
        case PAGE_NOACCESS:          p = "----"; break;
    }
    return(p);
}

PCTSTR GetMemStorageText(MEMORY_BASIC_INFORMATION mbi)
{
   PCTSTR p = TEXT("Unknown");

   switch (mbi.State)
   {
        case MEM_FREE:      p = "Free";     break;
        case MEM_RESERVE:       p = "Reserve";  break;
        case MEM_COMMIT:
            switch (mbi.Type)
            {
                case MEM_FREE:  p = "Free";     break;
                case MEM_RESERVE:   p = "Reserve";  break;
                case MEM_IMAGE: p = "Image";    break;
                case MEM_MAPPED:    p = "Mapped";   break;
                case MEM_PRIVATE:   p = "Private";  break;
            }
            break;
   }
   return(p);
}

VOID MemoryMap()
{
    DWORD dwProcessId = GetCurrentProcessId(),
    dwNeeded = 0;
    HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwProcessId);
    HMODULE lpModule[40];  //handle to a module
    LPVOID lpModuleAddress[40];
    MODULEINFO ModuleInfo; //structure contains the module load address, size, and entry point. 

    EnumProcessModules(hProcess, lpModule, sizeof(HMODULE)*40, &dwNeeded);

    dwNeeded /= sizeof(HMODULE);

    for(UINT i = 0;i < dwNeeded;i++)
    {
        GetModuleInformation(hProcess, lpModule[i], &ModuleInfo, sizeof(ModuleInfo));
        lpModuleAddress[i] = ModuleInfo.lpBaseOfDll;
    }

    MEMORY_BASIC_INFORMATION mbi; //structure contains information about a range of                       //pages in the virtual address space of a process
    PVOID lpAddress = NULL;

    printf("  Address\tBlok Size\tStorage\t\tProtect\n");
    CHAR str[255];

    while(VirtualQueryEx(hProcess, lpAddress, &mbi, sizeof(mbi)))
    {
        if(!(((UINT)lpAddress) % 0x10000))
        {
            printf("0x%p\t\t\t%s", lpAddress, GetMemStorageText(mbi));
            for(int i = 0;i < 5;i++)
                if(myblock[i] == lpAddress && alloc) printf("\n(My Al-location Block)");

            for(int i = 0;i < dwNeeded;i++)
                if(lpAddress == lpModuleAddress[i])
                {
                    GetModuleFileName(lpModule[i], str, 255);
                    printf("\n(Image: %s)", str);
                }
            printf("\n");
        }
        printf("  0x%p\t0x%p\t%s\t\t%s\n", lpAddress, (DWORD)mbi.RegionSize,
            GetMemStorageText(mbi), GetProtectText(mbi));
        lpAddress = ((PBYTE)lpAddress + mbi.RegionSize);
    };
}

VOID Allocation()
{
    alloc = TRUE;
    myblock[0] = VirtualAlloc(NULL, 1024, MEM_RESERVE, PAGE_READONLY);
    myblock[1] = VirtualAlloc(NULL, 1024*2, MEM_RESERVE, PAGE_READWRITE);
    myblock[2] = VirtualAlloc(NULL, 1024*8, MEM_RESERVE, PAGE_EXECUTE);
    myblock[3] = VirtualAlloc(NULL, 1024*16, MEM_RESERVE|MEM_COMMIT, PAGE_EXECUTE_READ);
    myblock[4] = VirtualAlloc(NULL, 1024*16, MEM_RESERVE|MEM_COMMIT, PAGE_EXECUTE_READWRITE);
}

VOID Release()
{
    for(int i = 0;i < 5;i++)
        VirtualFree(myblock[i], 0, MEM_RELEASE);
    alloc = FALSE;
}



INT _tmain(INT argc, _TCHAR* argv[])
{
    printf("\nProcess Virtual Memory Before Allocation Memory:\n");
    MemoryMap();
    printf("\nProcess Virtual Memory After Allocation Memory:\n");
    Allocation();
    MemoryMap();
    printf("\nProcess Virtual Memory After Release Memory:\n");
    Release();
    MemoryMap();
    getch();
    return 0;
}

1>------ Build started: Project: VirtMemory, Configuration: Debug Win32 ------
1>Build started 06.10.2011 23:51:01.
1>InitializeBuildStatus:
1>  Touching ".\Debug\VirtMemory.unsuccessfulbuild".
1>ClCompile:
1>  VirtMemory.cpp
1>e:\виртуальная память\kod1\virtmemory.cpp(80): warning C4018: '<' : signed/unsigned mismatch
1>e:\виртуальная память\kod1\virtmemory.cpp(123): warning C4996: 'getch': The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _getch. See online help for details.
1>          d:\program files\microsoft visual studio 10.0\vc\include\conio.h(128) : see declaration of 'getch'
1>ManifestResourceCompile:
1>  All outputs are up-to-date.
1>VirtMemory.obj : error LNK2019: unresolved external symbol _GetModuleInformation@16 referenced in function "void __cdecl MemoryMap(void)" (?MemoryMap@@YAXXZ)
1>VirtMemory.obj : error LNK2019: unresolved external symbol _EnumProcessModules@16 referenced in function "void __cdecl MemoryMap(void)" (?MemoryMap@@YAXXZ)
1>.\Debug\VirtMemory.exe : fatal error LNK1120: 2 unresolved externals
1>
1>Build FAILED.
1>
1>Time Elapsed 00:00:01.43
enter code here

推荐答案

GetModuleInformation &EnumProcessModules 将要求您正确包含并链接 psapi.lib

GetModuleInformation & EnumProcessModules will require that you properly include and link with psapi.lib

您可以在项目顶部轻松添加:

You can do so easily at the top of your project add:

#include <Psapi.h>
#pragma comment(lib, "psapi.lib")

这篇关于虚拟内存示例代码 WinApi C++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆