1

我正在尝试在资源文件.rc 中实现一个字符串表,然后使用函数 CString::LoadStringW() 加载特定的字符串。这是代码 main.cpp:

#ifndef _AFXDLL
#define _AFXDLL
#endif
#include <afx.h>
#include <stdio.h>
#include "resource.h"

int main()
{
    printf("Code Example: Load resource file data\n");

    CString sentence;
    sentence.LoadStringW(IDS_STRING101);
    printf("Sentence: %s", sentence);

    getchar();
    return 0;
}

已经有很好的链接描述,如何使用资源文件:

http://www.cplusplus.com/forum/windows/119338/

http://www.winprog.org/tutorial/resources.html

问题是当我编译代码然后尝试运行时,它不会读取字符串。调试时,带有 LoadStringW() 函数的行会抛出断言错误:

Debug Assertion Failed!

Program: C:\WINDOWS\SYSTEM32\mfc140ud.dll
File: f:\dd\vctools\vc7libs\ship\atlmfc\include\afxwin1.inl
Line: 24

For information on how your program can cause an assertion
failure, see the Visual C++ documentation on asserts.

在我提供的第一个 URL 的末尾(作为最后一步)链接已编译的资源文件 .rc 和我的源文件 main.cpp。我不确定如何执行此操作,也许这就是我的程序无法按预期工作的原因。

请问,你有什么建议吗?

我正在尝试 MSVS 2015 / 2017。

谢谢。

4

1 回答 1

0

过了一会儿,我仍然无法解释为什么有问题的代码不起作用。然而,为了从字符串表中读取字符串资源,我使用了不同的函数LoadString()并最终使它工作,这实际上不是CString类的一部分。

通过获取包含这些资源的正在运行的 .exe 文件的句柄来解决 NULL 资源处理程序的问题(验证包含哪些资源的好工具是例如 Resource Hacker) - 完成GetModuleHandle(NULL)

下面是工作代码片段。

主.cpp:

#include <afx.h>
#include <stdio.h>
#include "resource.h"
#define BUF_SIZE 50

int main(void)
{
    printf("Code Example: Load resource file data\n");

    wchar_t buffer[BUF_SIZE];

    if (!LoadString(GetModuleHandle(NULL), IDS_STRING104, buffer, BUF_SIZE))
    {
        printf("Error Loading String: IDS_STRING104\n");
    }
    else
    {
        printf("resource string: %ls\n", buffer);
    }

    getchar();
    return 0;
}

资源.h:

#define IDS_STRING103                   103
#define IDS_STRING104                   104

资源.rc:

#include "resource.h"

STRINGTABLE
BEGIN
    IDS_STRING103           "Resource 103 sentence"
    IDS_STRING104           "Resource 104 sentence"
END

以下是一些对我有用的参考资料:

如何获取我自己代码的模块句柄?

https://msdn.microsoft.com/en-gb/library/windows/desktop/ms647486.aspx

于 2017-10-03T08:40:12.393 回答