C++/CX - 我需要将一个 Platform::String 传递到一个接受常量字符*的方法中
C++/CX - I need to pass a Platform::String into a method that takes a const char*?
我是 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
。
相关文章:
- 不能将方法返回的值用于另一个方法
- C++有没有办法强制重写一组方法,如果其中一个方法在子类中具有重写?
- 我在C++中编写了一个方法来打印树类的预序,但它显示了分割错误
- 重写另一个方法 [C++] 使用的超类回调函数
- C++:如何使用传递引用在一个方法中返回多个值
- 为什么一个方法对同一个变量有常量和非常量参数?
- 从同一类中的另一个方法调用方法时出错
- 向现有类添加一个方法以逐行读取文件的内容
- 无法从派生的一个方法调用基类方法
- 如何将一个方法中的值返回到同一类的另一个方法
- 方法重载 C++ -> 只有一个方法调用
- 在另一个线程中执行一个方法
- 是否可以在另一个方法中使用模板类中定义的虚拟方法
- 调用方法,该方法修改字段,而使用该字段的另一个方法正在执行
- 将一个方法作为参数传递给另一个方法,该方法本身将传递的方法传递给 std 线程
- 仅专用于模板类的一个方法(部分)
- 确定一个方法是否是纯虚拟的(c++)
- 是否可以判断一个方法在编译时是否可以公开访问
- 我正在尝试创建一个方法,该方法使用指针算术返回一对,它是否会出错
- 从 ndk 中的 jni 方法调用另一个C++方法