我很好奇在访问返回可变长度结构的 Win32 API 时使用联合是否是个好主意,以避免手动管理分配的内存。
考虑以下:
void displayServices(std::wostream& log, std::tr1::shared_ptr<void> manager, LPENUM_SERVICE_STATUS currentServiceToDisplay, DWORD number, bool whitelist)
{
static union //Don't care about being thread safe
{
QUERY_SERVICE_CONFIG svcConfig;
unsigned char bufferSizer[8000];
};
for(DWORD idx = 0; idx < number; currentServiceToDisplay++, idx++)
{
DWORD garbage = 0;
std::tr1::shared_ptr<void> currentServiceHandle(
OpenService(reinterpret_cast<SC_HANDLE>(manager.get()), currentServiceToDisplay->lpServiceName, SERVICE_QUERY_CONFIG),
serviceCloser);
QueryServiceConfig(reinterpret_cast<SC_HANDLE>(currentServiceHandle.get()),
&svcConfig, 8000, &garbage);
//Use svcConfig for something here.
}
}
这有什么大问题吗?