You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将std::string.data()返回的const char*转换为Windows C++的Array<unsigned char>?

将std::string的const char*转换为Windows C++的Array以适配DataWriter::WriteBytes()

要把std::string通过data()得到的const char*转换成通用Windows C++的Platform::Array<unsigned char>^(适配DataWriter::WriteBytes()的参数要求),直接基于内存拷贝即可——因为char和unsigned char的内存存储格式兼容,无需额外编码转换(如果只是要原封不动的字节流)。

具体实现代码

#include <string>
#include <cstring>
// 需包含UWP相关头文件(如 <windows.h> 或 <winrt/Windows.Storage.Streams.h> 等)

// 示例std::string对象
std::string sourceStr = "需要转换的字符串内容";

// 获取原始数据指针和长度
const char* rawBytes = sourceStr.data();
size_t byteCount = sourceStr.size();

// 创建Platform::Array<unsigned char>并拷贝数据
Platform::Array<unsigned char>^ targetArray = ref new Platform::Array<unsigned char>(byteCount);
std::memcpy(targetArray->Data, rawBytes, byteCount);

// 传入DataWriter::WriteBytes方法
dataWriter->WriteBytes(targetArray);

关键说明

  • std::memcpy直接内存拷贝是安全的,char和unsigned char仅在类型语义上有区别,内存中的字节值完全一致。
  • 如果你的std::string存储的是UTF-8编码内容,转换后的Array<unsigned char>会保留原始UTF-8字节流,可直接通过WriteBytes写入。若需转换为UTF-16字节流,需额外调用MultiByteToWideChar等API处理后再拷贝。
  • 确保sourceStr在拷贝过程中生命周期有效,避免使用已销毁字符串的data()指针。

内容的提问来源于stack exchange,提问作者JaSHin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 14:54:22