c - 枚举 DirectSound 设备描述导致不必要的问号

标签 c visual-studio winapi outputdebugstring

我正在枚举所有 DirectSound 输出设备并存储它们的描述以供以后在我的进程运行时使用。当我使用 OutputDebugStringW 检查结果时,我得到了正确的设备名称,但附加了不必要的问号。即这个...

BOOL CALLBACK AudioPrivate::DSEnumProc(LPGUID lpGUID,
                                       LPCWSTR lpszDesc,
                                       LPCWSTR lpszDevName,
                                       LPVOID lpData) {
    pDeviceInfo[nDevices].lpGUID = lpGUID;
    pDeviceInfo[nDevices].lpszDesc = new WCHAR[wcslen(lpszDesc)];
    pDeviceInfo[nDevices].lpszDevName = new WCHAR[wcslen(lpszDevName)];

    ZeroMemory(pDeviceInfo[nDevices].lpszDesc, sizeof(WCHAR) * wcslen(lpszDesc));
    ZeroMemory(pDeviceInfo[nDevices].lpszDevName, sizeof(WCHAR) * wcslen(lpszDevName));

    memcpy(pDeviceInfo[nDevices].lpszDesc, lpszDesc, sizeof(WCHAR) * wcslen(lpszDesc));
    memcpy(pDeviceInfo[nDevices].lpszDevName, lpszDevName, sizeof(WCHAR) * wcslen(lpszDevName));

    OutputDebugStringW(L"\n");
    OutputDebugStringW(pDeviceInfo[nDevices].lpszDesc);
    OutputDebugStringW(L"\n");
    OutputDebugStringW(pDeviceInfo[nDevices].lpszDevName);
    OutputDebugStringW(L"\n");

    //vs
    OutputDebugString(L"\n");
    OutputDebugStringW(lpszDesc);
    OutputDebugStringW(L"\n");
    OutputDebugStringW(lpszDevName);
    OutputDebugStringW(L"\n");

    nDevices++;

    return TRUE;
}

...结果如下:

Primary Sound Driver????????????
????????

Primary Sound Driver



Speakers (Conexant SmartAudio HD)???????????
{0.0.0.00000000}.{0698bbc7-d0ba-4445-a5a7-a63b625c4298}?????????

Speakers (Conexant SmartAudio HD)
{0.0.0.00000000}.{0698bbc7-d0ba-4445-a5a7-a63b625c4298}

我正在清空我自己的字符串的内存,所以只有当 Enum Proc 提供的字符串中有这些问号时才会发生这种情况,但正如所证明的那样,它们没有。为什么会这样?

最佳答案

您必须为字符串终止符(也包括 NULL 字符)保留空间,此行将只为字符串分配空间,没有终止符:

pDeviceInfo[nDevices].lpszDesc = new WCHAR[wcslen(lpszDesc)];

这是因为 wcslen() 返回不带终止符的字符串长度(参见 reference )。只需更改为(当然对于所有字符串):

pDeviceInfo[nDevices].lpszDesc = new WCHAR[wcslen(lpszDesc) + 1];
pDeviceInfo[nDevices].lpszDevName = new WCHAR[wcslen(lpszDevName) + 1];

和:

ZeroMemory(pDeviceInfo[nDevices].lpszDesc, sizeof(WCHAR) * (wcslen(lpszDesc) + 1));
ZeroMemory(pDeviceInfo[nDevices].lpszDevName, sizeof(WCHAR) * (wcslen(lpszDevName) + 1));

关于c - 枚举 DirectSound 设备描述导致不必要的问号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20925865/

相关文章:

c - Windows 中的多线程 - 创建函数指针数组时出错

c++ - 如何在旧版驱动程序中使用 PE header 进行用户修改后获取原始文件类型

c - 我使用埃拉托色尼筛作为素性测试。为什么我得到 2297 是复合数?

c - C 语言的预处理器

c# - 从命令行在解决方案中仅构建一个项目

visual-studio - 从 Qt SDK 包管理器为 Visual Studio 安装 Qt 插件

visual-studio - 在 visual studio 2017 中安装 xunit.net

C-错误 : array type has incomplete element type in a extern struct declaration

memset 可以在 4 核上并行化吗?

delphi - 如何从Delphi获取服务器正在使用的端口列表