C++/CX - 我需要将一个 Platform::String 传递到一个接受常量字符*的方法中

C++/CX - I need to pass a Platform::String into a method that takes a const char*?

本文关键字:一个 方法 常量 字符 Platform CX String C++      更新时间:2023-10-16

我是 c++ 的新手(我是 c# 开发人员)。

我有一个SQLite包装类,要求您传入数据库名称作为const char*,但是我只将其作为Platform::String(在进行文件搜索之后)。

我似乎找不到将Platform::String转换为const char*的方法.

我在StackOverflow上看到了另一个问题,解释了为什么它不是直截了当的,但没有示例代码或端到端解决方案。

谁能帮我?

谢谢

免责声明:我对 C++/CX 知之甚少,我的答案是基于这里的文档。

String类包含 16 位 Unicode 字符,因此无法直接获取指向 8 位char类型字符的指针;您需要转换内容。

如果已知字符串仅包含 ASCII 字符,则可以直接转换它:

String s = whatever();
std::string narrow(s.Begin(), s.End());
function_requiring_cstring(narrow.c_str());

否则,字符串将需要翻译,这变得相当毛茸茸的。以下内容可能会做正确的事情,将宽字符转换为窄字符的多字节序列:

String s = whatever();
std::wstring wide(s.Begin(), s.End());
std::vector<char> buffer(s.Length()+1);  // We'll need at least that much
for (;;) {
    size_t length = std::wcstombs(buffer.data(), wide.c_str(), buffer.size());
    if (length == buffer.size()) {
        buffer.resize(buffer.size()*2);
    } else {
        buffer.resize(length+1);
        break;
    }
}
function_requiring_cstring(buffer.data());

或者,您可能会发现更容易忽略Microsoft关于如何处理字符串的想法,而改用std::string