0

在 c# 中使用此代码:

WindowsIdentity.GetCurrent().User.Value;

并获得输出:

S-1-5-21-3050176684-2277112922-4090480026-1001

如何在 C++ 中获得相同的输出?

4

1 回答 1

0

以下是有关如何使用LookupAccountName链接到 API)在本地计算机上获取帐户名的 SID 的一些代码:

#include <windows.h>
#include <iostream>
#include <sddl.h>

LPCWSTR GetSid(LPCWSTR szAccountName)
{
    LPWSTR pszRet = NULL;

    DWORD dwDomainSize = 32, dwSidSize = 32;
    LPWSTR pszDomainName = new WCHAR[dwDomainSize];
    unsigned char* pSid = new unsigned char[dwSidSize];

    while (true)
    {
        SID_NAME_USE sidType;
        DWORD dwDomainSizeTmp = dwDomainSize, dwSidSizeTmp = dwSidSize;
        if (LookupAccountNameW(NULL, szAccountName, (PSID)pSid,
            &dwSidSizeTmp, pszDomainName, &dwDomainSizeTmp, &sidType))
        {
            LPWSTR pszTmp;
            if (ConvertSidToStringSidW(pSid, &pszTmp))
            {
                const int buffLen = wcslen(pszTmp) + 1;
                pszRet = new WCHAR[buffLen];
                wcscpy_s(pszRet, buffLen, pszTmp);
                LocalFree(pszTmp);
            }
            break;
        }
        else
        {
            if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
            {
                if (dwDomainSizeTmp > dwDomainSize)
                {
                    delete[] pszDomainName;
                    pszDomainName = new WCHAR[dwDomainSizeTmp];
                    dwDomainSize = dwDomainSizeTmp;
                }
                if (dwSidSizeTmp > dwSidSize)
                {
                    delete[] pSid;
                    pSid = new unsigned char[dwSidSizeTmp];
                    dwSidSize = dwSidSizeTmp;
                }
            }
            else
            {
                break;
            }
        }
    }

    delete[] pszDomainName;
    delete[] pSid;

    return pszRet;
}

int main()
{
    LPCWSTR ret = GetSid(L"andy");
    if (ret)
    {
        std::wcout << L"SID for \"andy\" is: " << ret << std::endl;
        delete[] ret;
    }
    else
    {
        std::wcout << L"Failed to get SID for \"andy\"" << std::endl;
    }
    return 0;
}
于 2020-10-04T03:17:40.473 回答