防止运算符被插入到字符串流中

Prevent operators from being inserted into stringstream

免责声明:我对 C++ 很糟糕;

我正在使用 wstringstream 从向量中获取对象并将它们的值格式化为可以存储在 'file map'(对于 IPC)中的字符串。

std::wstringstream ss;
SDLWrap::frame obs = SDLWrap::getObs();
for (int i = 0; i < obs.pixels.size(); i++ )
{
    SDLWrap::pixel p = obs.pixels[i];
    ss << "{" << p.x << "," << p.y << "," << p.r << "," << p.g << "," << p.b << "}";
}
MemFile::writeMemData(TEXT("Local\ReflexAIOut"), ss.str(), ss.str().length()*2);

将字符串转换为字符数组(WCHAR),然后放入内存。似乎运算符也包含在字符串中,因为最终结果包含 3 个 NUL 字符来代替运算符。

<mmap.mmap object at 0x00000185F9A8CF30>
b'{\x000\x00,\x000\x00,\x000\x00,\x000\x00,\x000\x00}\x00{\x000\x00,\x001\x00,\x000\x00,\x000\x00,\x000\x00}\x00{\x000\x00,\x002\x00,\x000\x00,\x000\x00,\x000\x00}...

有没有一种简单的方法可以在不包括运算符的情况下连接这些值?我想避免必须进行另一个循环来删除额外的 NUL 字符。

编辑:这是 writeMemData 函数

bool MemFile::writeMemData(std::wstring memName, std::wstring data, int size)
{
    HANDLE mapFile;
    LPCTSTR buff;

    mapFile = CreateFileMapping(
        INVALID_HANDLE_VALUE,
        NULL,
        PAGE_READWRITE,
        0,
        size,
        memName.c_str());

    if (mapFile == NULL)
    {
        return false;
    }

    buff = (LPTSTR)MapViewOfFile(mapFile,
        FILE_MAP_ALL_ACCESS,
        0,
        0,
        size);

    if (buff == NULL)
    {
        return false;
    }

    CopyMemory((PVOID)buff, data.c_str(), (_tcslen(data.c_str()) * sizeof(TCHAR)));

    UnmapViewOfFile(buff);
    openMem_.push_back(mapFile);
}

您正在写入 std::wstringstream,它是 (在您的情况下为 16 位或 2 字节*)字符流。因此,对于每个放入该流的 1 字节 char,都会输出 2 字节 wchar_t

ss << "{" << p.x << "," << p.y << "," << p.r << "," << p.g << "," << p.b << "}";
//     |     |       |     |       |     |       |     |       |     |       |
//     {\x00 0\x00   ,\x00 0\x00   ,\x00 0\x00   ,\x00 0\x00   ,\x00 0\x00   }\x00

那些 NUL 字节是 2 个字节对的高字节。

如果您希望数据以 8 位编码进行编码,请使用 std::stringstream 而不是 std::wstringstream

* - 标准未定义确切的 wchar_t 大小。