技术开发 频道

C++程序开发 让你的代码足够的强大!

  检查函数的返回代码

  断定一个函数执行一定成功是一种常见的错误。当你调用一个函数的时候,建议检查下返回代码和返回参数的值。如下代码持续调用Windows API ,程序是否继续执行下去依赖于该函数的返回结果和返回参数值。

HRESULT hres = E_FAIL;
IWbemServices
*pSvc = NULL;
IWbemLocator
*pLoc = NULL;
hres
= CoInitializeSecurity(
NULL,
-1, // COM authentication
NULL, // Authentication services
NULL, // Reserved
RPC_C_AUTHN_LEVEL_DEFAULT, // Default authentication
RPC_C_IMP_LEVEL_IMPERSONATE, // Default Impersonation
NULL, // Authentication info
EOAC_NONE, // Additional capabilities
NULL // Reserved
);
if (FAILED(hres))
{
// Failed to initialize security
if(hres!=RPC_E_TOO_LATE)
return FALSE;
}
hres
= CoCreateInstance(
CLSID_WbemLocator,
0,
CLSCTX_INPROC_SERVER,
IID_IWbemLocator, (LPVOID
*) &pLoc);
if (FAILED(hres) || !pLoc)
{
// Failed to create IWbemLocator object.
return FALSE;
}
hres
= pLoc->ConnectServer(
_bstr_t(L
"ROOT\\CIMV2"), // Object path of WMI namespace
NULL, // User name. NULL = current user
NULL, // User password. NULL = current
0, // Locale. NULL indicates current
NULL, // Security flags.
0, // Authority (e.g. Kerberos)
0, // Context object
&pSvc // pointer to IWbemServices proxy
);
if (FAILED(hres) || !pSvc)
{
// Couldn't conect server
if(pLoc) pLoc->Release();
return FALSE;
}
hres
= CoSetProxyBlanket(
pSvc,
// Indicates the proxy to set
RPC_C_AUTHN_WINNT, // RPC_C_AUTHN_xxx
RPC_C_AUTHZ_NONE, // RPC_C_AUTHZ_xxx
NULL, // Server principal name
RPC_C_AUTHN_LEVEL_CALL, // RPC_C_AUTHN_LEVEL_xxx
RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx
NULL, // client identity
EOAC_NONE // proxy capabilities
);
if (FAILED(hres))
{
// Could not set proxy blanket.
if(pSvc) pSvc->Release();
if(pLoc) pLoc->Release();
return FALSE;
}
0
相关文章