c++递归地通过注册表循环是s

2024-06-16 12:49:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码有一个恼人的问题,可能是我做错了什么,因为我的Python 实现速度快得多!在

C++实现问题:

  1. 迭代“HKEY_CLASSES_ROOT”需要大量ram,我想这是因为c++实现使用了很多变量。固定
  2. 它也很慢,比python植入代码的速度慢得多
  3. 当试图迭代HKEY_CLASSES_ROOTFixed时,代码甚至会慢下来

新问题:

  1. 多亏了Nam Nguyen我了解了是什么导致了我的代码中的漏洞,并直接影响了执行时间,下面的代码是固定的。为什么c++实现的运行速度和我的python实现一样快?在

C++实现:

#include <iostream>
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#include <string>

using namespace std;

#define MAX_KEY_LENGTH 255

int RecurseOpenRegEx(HKEY hkey, string subKey = "",string search = "nothing", DWORD sum = 0)
{
   TCHAR csubKey[MAX_KEY_LENGTH];
   DWORD nSubKeys = 0;
   DWORD pathLength = MAX_PATH;
   TCHAR storeKeyName[MAX_KEY_LENGTH];
   DWORD keyLength;
   HKEY hKey = hkey; //somehow i need to reassign HKEY, otherwise it won't pass it with the function, this is bigger than me tough...

   const char * ccsearch = search.c_str();
   const char * ccsubKey;


   if (subKey != "")
   {
       ccsubKey = subKey.c_str();
       copy(subKey.begin(), subKey.end(),csubKey); //convert string to TCHAR
   }

   if (RegOpenKeyEx(hkey, ccsubKey, 0, KEY_READ, &hkey) == ERROR_SUCCESS)
   {
       if (RegQueryInfoKey(hkey, csubKey, &pathLength, NULL,&nSubKeys, NULL, NULL, NULL, NULL, NULL, NULL, NULL) == ERROR_SUCCESS)
       {
           sum += nSubKeys;
           for (DWORD subKeyIndex = 0; subKeyIndex < nSubKeys; subKeyIndex++)
           {
               keyLength = MAX_KEY_LENGTH;
               if (RegEnumKeyEx(hkey, subKeyIndex, storeKeyName, &keyLength, NULL, NULL, NULL, NULL) == ERROR_SUCCESS)
               {
                   string sKeyName = storeKeyName; //Convert TCHAR to string explicitly


                   if (subKey != "")
                   {
                       sKeyName = subKey + "\\" + sKeyName;
                   }
                   sum += RecurseOpenRegEx(hKey, sKeyName);
               }
           }
       }
   }
   RegCloseKey(hkey); //Now closing the right key
   return sum;
}

int main()
{
   cout << "sum of all keys: " << RecurseOpenRegEx(HKEY_LOCAL_MACHINE);
   return 0;
}

Python实现:

^{pr2}$

Tags: key代码stringifincludenulllengthmax
2条回答

您的代码中存在资源泄漏。打开hkey,但关闭{}(注意k和{}的区别)。在

另一方面,您将打开的注册表项存储到hkey本身。碰巧hkey是传入的参数,在对RecurseOpenRegEx的所有调用中共享。这就是为什么“不知何故我需要重新分配HKEY”。在

基本上,我现在能建议你的是立即清理你的代码。当你的代码太难阅读时,这样的错误很难被发现。一旦完成,我相信您会发现调试/跟踪更容易。在

可能是您大量使用字符串变量,这涉及到大量的动态内存分配。在

尝试将参数接受为LPCTSTR。使用这些LPCTSTR在函数内分配字符串变量,并使用str.c_str()传递参数。在

相关问题 更多 >