// testWin32Console.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <Windows.h>
#include <tchar.h>
#include <string>
void fnTest();
int _tmain(int argc, _TCHAR* argv[])
{
fnTest();
/// run result
/**
strBufSrc.size() = 260
strBufDst.size() = 260
verify ok, std::string can use as binary array
*/
/// 通过试验,可以看出 std::string 可以当二进制数组用
getwchar();
return 0;
}
void fnTest()
{
/// 在一个工程中看到用std::string resize + memcpy 当二进制数组用
/// 当需要赋值到另外一个string时,是采用原生的'= '操作符,还是自己拷贝呢
/// 如果自己(resize + memcpy)拷贝的话,是可以的
/// 如果用 '=' 操作符, 不能确定, 验证一下
size_t nIndex = 0;
std::string strBufSrc = "";
std::string strBufDst = "";
UCHAR uBuf[MAX_PATH] = {'\0'};
/// 对uBuf赋值,模拟是一个二进制文件的内容
for (nIndex = 0; nIndex < sizeof(uBuf); nIndex++)
{
uBuf[nIndex] = (0xff - nIndex) % 0xff; ///< 255 ~ 1
}
/// 对src赋值
strBufSrc.resize(sizeof(uBuf));
::memcpy((PVOID)strBufSrc.data(), uBuf, sizeof(uBuf));
/// 用src对dst赋值
strBufDst = strBufSrc;
_tprintf(L"strBufSrc.size() = %d\r\n", strBufSrc.size());
_tprintf(L"strBufDst.size() = %d\r\n", strBufDst.size());
if (strBufDst.size() != strBufSrc.size())
{
_tprintf(L"verify failed, can't use std::string as binary array by \"=\"\r\n");
return;
}
else
{
/// 逐个字节验证,看是否相同
for (nIndex = 0; nIndex < strBufSrc.size(); nIndex++)
{
if (strBufSrc[nIndex] != strBufDst[nIndex])
{
/// failed
_tprintf(L"failed : nIndex = %d, src char[0x%X] <=> dst char[0x%X]\r\n");
return;
}
}
}
_tprintf(L"verify ok, std::string can use as binary array\r\n");
}
STL : std::string可以当UCHAR数组用
最新推荐文章于 2025-07-03 14:45:15 发布