【问题标题】:changing const wchar_t* during runtime在运行时更改 const wchar_t*
【发布时间】:2020-03-10 09:33:23
【问题描述】:

我有一个使用 std::cin 收到的字符串,我试图将 const wchar_t* 更改为该变量

const wchar_t* TARGET_FILE = L"";
try {
    std::string str;
    std::cout << "DLL Name: ";
    getline(std::cin, str);
    //TARGET_FILE = str;
    std::string narrow_string(str);
    std::wstring wide_string = std::wstring(narrow_string.begin(), narrow_string.end());
    const wchar_t* result = wide_string.c_str();
    const wchar_t* TARGET_FILE = result;
    std::cout << TARGET_FILE; //Debug

}
catch (const std::exception & ex) {
    std::cout << "[ERROR] " << ex.what() << '\n';
    std::cout << "Press any key to exit..." << '\n';
    std::cin.get();
    return EXIT_FAILURE;
}

当这段代码被执行时,会发生这种情况

DLL Name: Kinky.dll
0000020E11C61560[ERROR] DLL not found.
Press any key to exit...

当我使用硬编码 TARGET_FILE 的值时,我得到 0000019CCB971300 而不是有效的文本格式

//constexpr auto TARGET_FILE      = L"Kinky.dll";

对不起,如果我有点愚蠢,但我不太熟悉 wchar_t vars 是什么,我只知道我使用的 sdk 需要一个

编辑: 本部分由我粘贴以尝试解决原始问题,所以如果它的正确用法如果它不正确的用法我希望这是我的问题

std::string narrow_string(str);
std::wstring wide_string = std::wstring(narrow_string.begin(), narrow_string.end());
const wchar_t* result = wide_string.c_str();
const wchar_t* TARGET_FILE = result;

【问题讨论】:

  • 这真的是产生运行时错误的代码吗?您有两个不同的 TARGET_FILE 变量,一个隐藏另一个,更改第一个的定义不应该有任何影响
  • 使用std::wcout 打印宽字符。
  • 您将 TARGET_FILE 作为全局变量和局部变量。这可能与您的问题有很大关系。
  • 也许运行时错误仅由您未显示的代码引起,该代码假定第一个 TARGET_FILE 变量包含文件名,但实际上您从未修改它。确保minimal reproducible example 是必需的
  • 尝试在 try-catch 之外添加一个std::cout &lt;&lt; TARGET_FILE; //Debug,这应该可以解决这个问题

标签: c++


【解决方案1】:

您可以先读取宽字符,而不是转换字符串。使用std::wcin 读取和std::wcout 打印宽字符。您可以将文本保留为std::wstring,并在调用需要const wchar_t*的函数时使用c_str()

void function1(const wchar_t*);

void function2() {
    std::wstring str;
    getline(std::wcin, str);
    std::wcout << str;

    function1(str.c_str());
}

【讨论】:

  • 感谢我不得不在我的其余代码中更改一些东西,但这非常有效,谢谢:)
【解决方案2】:

两个问题:

1) 潜在的问题是如何将窄字符串转换为宽字符串。当您转换 ASCII dll 名称时,一切都很好(或者不是?我猜只是在实践中?)。否则有龙。转换为宽字符很难:您应该以某种方式知道窄编码(UTF-8?系统编码?),宽字符编码在不同平台上也不同(Windows 上的 USC-2 或 UTF-16,Linux 上的 UTF-32,本机字节序)。但这是不同的问题。

2) 正确答案(@Ville-Valteri 提到的)是您不能将const wchar* 输出到std::coutcout 把它当作一个指针,而你得到的这个 00007FF6A958CAF0 就是一个指针值。这不是你想要的。也许您想写入 std::wcout,或者转换回窄字符串;你需要什么取决于你的实际代码。

【讨论】:

  • 我所需要的只是引用文件名,这样我就可以将 dll 加载到另一个应用程序中,感谢更具体的错误原因
  • FWIW 如果你需要 std::string,你可以试试 ANSI 等价物,比如 LoadLibraryA()
猜你喜欢
  • 1970-01-01
  • 2015-06-26
  • 2011-07-29
  • 2015-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-04
  • 1970-01-01
相关资源
最近更新 更多