我的代码有一个恼人的问题,可能是我做错了什么,因为我的Python 实现速度快得多!在
C++实现问题:
新问题:
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}$
您的代码中存在资源泄漏。打开}(注意}的区别)。在
hkey
,但关闭{k
和{另一方面,您将打开的注册表项存储到
hkey
本身。碰巧hkey
是传入的参数,在对RecurseOpenRegEx
的所有调用中共享。这就是为什么“不知何故我需要重新分配HKEY”。在基本上,我现在能建议你的是立即清理你的代码。当你的代码太难阅读时,这样的错误很难被发现。一旦完成,我相信您会发现调试/跟踪更容易。在
可能是您大量使用字符串变量,这涉及到大量的动态内存分配。在
尝试将参数接受为LPCTSTR。使用这些LPCTSTR在函数内分配字符串变量,并使用str.c_str()传递参数。在
相关问题 更多 >
编程相关推荐