c++ - GetComputerName() 返回空结果

标签 c++ windows winapi

我正在尝试在我的 C++ 应用程序中使用 GetComputerName() 函数,但无法使其正常工作。这是我的代码:

.h:

#pragma once

class sample
{
public:
    sample();
    char* get_info_pcName();
    ~sample();
private:
    char* info_pcName;
};

.cpp:

#include "sample.h"

#include <windows.h>

sample::sample()
{
    this->info_pcName = 0;
}

char* sample::get_info_pcName()
{
    if (info_pcName)
        return this->info_pcName;

    this->info_pcName = new char[MAX_COMPUTERNAME_LENGTH + 1];
    DWORD nComputerName = sizeof(this->info_pcName);
    if (!GetComputerName(this->info_pcName, &nComputerName))
    this->info_pcName = "error";

    return this->info_pcName;
}

这是怎么回事?我总是得到一个空的回应):

最佳答案

sizeof(this->info_pcName) 产生 char* 的大小(在您的系统上可能是 4 或 8),而不是数组的长度。以下应该有效:

char* sample::get_info_pcName()
{
    if (info_pcName)
        return info_pcName;

    DWORD nComputerName = MAX_COMPUTERNAME_LENGTH + 1;
    info_pcName = new char[nComputerName];
    if (!GetComputerName(info_pcName, &nComputerName))
        info_pcName = "error";

    return info_pcName;
}

另外,以这种方式使用原始指针是不好的做法。对于 C++03,我建议使用以下方法(对于 C++11,有更好的方法):

#include <cstring>
#include <vector>
#include <windows.h>

class sample
{
public:
    char const* get_info_pcName();

private:
    std::vector<char> info_pcName;
};

char const* sample::get_info_pcName()
{
    if (!info_pcName.empty())
        return &info_pcName[0];

    DWORD nComputerName = MAX_COMPUTERNAME_LENGTH + 1;
    info_pcName.resize(nComputerName);
    if (!GetComputerName(&info_pcName[0], &nComputerName))
        std::strcpy(&info_pcName[0], "error");

    return &info_pcName[0];
}

这样您就不需要手写的构造函数或析构函数,也不需要手写的复制构造函数或复制赋值运算符(您的类不正确地缺少这两者,这会导致任何正常使用时的内存损坏)。

关于c++ - GetComputerName() 返回空结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7828158/

相关文章:

java - 需要在类似于 CertSerializeCertificateStoreElement Windows API 的 java 中生成相同的序列化值

c++ - 在 Win32 控制台应用程序中显示弹出窗口

c++ - 即使缓冲区被未决操作覆盖,WriteFile 也成功

c++ - 将文件保存在 linux 的不同位置

c++ - 可以安全地使用指向 vector 元素的指针来确定它在容器中的位置吗?

c++ - 如何获取INT变量到QProcess写命令?

delphi - Delphi 使用哪些 Windows 消息来通知组合框中的更改?

c++ - 在 C++ 中定义常量 C 字符串的正确方法?

c# - 从 .NET 应用程序登录 Windows

c++ - AdjustTokenPrivileges 错误 ERROR_NOT_ALL_ASSIGNED